Tags
PHP
Asked 7 years ago
21 Oct 2016
Views 2556
denyy

denyy posted

how to check : file is zip or not in php ?

how to check file in zip or not in php , i am working for my one client who need website where people can upload there large data . they need to upload in .zip format so we can decompress zip file
i used following code to upload and to check file is zip or not by checking file 's extension ".zip" or not


$uploads_dir=dirname(__FILE__).DIRECTORY_SEPARATOR."upload".DIRECTORY_SEPARATOR;
$tmp_name = $_FILES["file"]["tmp_name"];
$name = basename($_FILES["file"]["name"]);
if(move_uploaded_file($tmp_name, "$uploads_dir/$name")){
	 //successfully uploaded 
	$filemetadata=pathinfo($name);
	if($filemetadata['extension']=='zip') {
	//extract zip 
	}
}


but extension checking for valid zip or not is not enough . sometime users upload not valid zip . so how to check is file is valid zip or not ?
if you try to unzip it by coding .it says itself . is it zip or not ? - Phpworker  
Oct 21 '16 12:05
no i want to check the zip file first , is it valid zip or not ? and than work for extract - denyy  
Oct 21 '16 12:09
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

you can check file is valid zip or not by following code


$zipcontent=file_get_contents("test.zip");
 
if (strpos($zipcontent, "\x50\x4b\x03\x04") === false)
{
	echo "it is not zip ";
}


so if in your code . you can put use like this

$uploads_dir=dirname(__FILE__).DIRECTORY_SEPARATOR."upload".DIRECTORY_SEPARATOR;
$tmp_name = $_FILES["file"]["tmp_name"];
$name = basename($_FILES["file"]["name"]);
if(move_uploaded_file($tmp_name, "$uploads_dir/$name")){
	 //successfully uploaded 
	$filemetadata=pathinfo($name);
	if($filemetadata['extension']=='zip') {
		//extra checking for zip validation
		$zipfilecontent=file_get_contents("$uploads_dir/$name");
		if (strpos($zipfilecontent, "\x50\x4b\x03\x04") === false)
		{
			echo "I AM NOT ZIP";
		}
		else {
			//extract it 
		}
	}
}

hope it work
Mahesh Radadiya

Mahesh Radadiya
answered Nov 30 '-1 00:00

i made function is_file_zip to check whether file is zip or not so use function is

function is_file_Zip($filename)
{
	//check is valid file or not  
	if(is_file($filename)==false){
		return false;
	}
	//check file extension match with .zip or not  
	if(pathinfo($filename,PATHINFO_EXTENSION )!='zip'){
		   return false;
	}
	$fileHeader="\x50\x4b\x03\x04";
	$data=file_get_contents($filename);
	if (strpos($data, $fileHeader) === false)
	{
		 return false;
	}
	return true;
}  



usage like this


if(is_file_zip("test.zip")){
//do something with zip . its really zip file
 
}
Post Answer