How to Zip a directory in PHP

Create zip file from directory in PHP; Through this tutorial, i am going to show you how to create zip file from directory in php, or php zip folder and subfolders, php create zip file and download, php zip addfile, php exec zip folder, php zip csv file,, zip archive, php zip archive extension, etc.

How to Zip a directory in PHP

Create a index.php file and add the following code into your index.php file to create zip file from directory or folder; is as follows:

/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		//add the files
		foreach($valid_files as $file) {
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
		//close the zip -- done!
		//check to make sure the file exists
		return file_exists($destination);
		return false;
$files_to_zip = array(
//if success than true. if false, zip creation failed
$result = create_zip($files_to_zip,'');

The PHP create_zip () is compresses and downloads files or folders into zip.

You will see that the function named create_zip () is called in the last of PHP script. This function compresses files and folders in the zip. And If you want to change the name of the zip file that will be created and downloaded, you can also change its name easily.

NOTE:- Where you create_zip ($ files_to_zip, ‘’); Under “” it has been done, instead you can keep any name you want to keep.

Now you have to go to the browser. And hit the following URL


The zip file we named “” was converted to such zip after downloading. You can see in the image below.

Recommended PHP Tutorials

Leave a Comment