How to create a zip file in php



In this post am going to explain, how to create a zip file in PHP of multiple files and force download the zip file. It is useful for some web projects, that providing the documents according to the selection of files like PDFs, images and docs etc and you can choose the files and download it in zip format.

Here is a simple php code to create a zip file by using php class ZipArchive, but that need ZIP extension to available. Following example requires an array of files with there path. After that it is checking if file is exists or not. Than it create the zip for the valid files and force to download of zip file named “zipfile.zip”.

$files = array(
	'files/Desert.jpg',
	'files/Hydrangeas.jpg',
	'files/Jellyfish.jpg'
);

$valid_files = array();
if(is_array($files)) {
	foreach($files as $file) {
		if(file_exists($file)) {
			$valid_files[] = $file;
		}
	}
}

if(count($valid_files > 0)){
	$zip = new ZipArchive();
	$zip_name = "zipfile.zip";
	if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
		$error .= "* Sorry ZIP creation failed at this time";
	}

	foreach($valid_files as $file){
		$zip->addFile($file);
	}

	$zip->close();
	if(file_exists($zip_name)){
		// force to download the zip
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false);
		header('Content-type: application/zip');
		header('Content-Disposition: attachment; filename="'.$zip_name.'"');
		readfile($zip_name);
		// remove zip file from temp path
		unlink($zip_name);
	}

} else {
	echo "No valid files to zip";
	exit;
}

This is a simple example to explain how to create a zip file in php, you can modify it for your purpose as you want.

ZipArchive::addFile ( string $filename [, string $localname = NULL ] )

filename - The path to the file to add.
localname- If you want to rename the file inside the ZIP archive that will override the filename.

Hope this may help you.

Demo

How to create a zip file in php
How to create a zip file in php