How To Create And Download A Zip File In PHP

By : PHPErrorCode October 8, 2017 234 Views php

Today, i create a smole php script to creat a zip archive file using ZipArchive class .we will be set the folder path to create a zip archive file and download zip archive file automatically. So here i will give you very simple example to do this.

In the many part of the website may require to create zip archive file using smole ZipArchive() php class. So here i am create a simple function createZip(), In which send two parameter ( that like $zip,$dir ). that will help to create zip archive file.

  • First create folder , like /myfolder/
  • $dir = 'myfolder/';

create and download zip:

Now you can run below example to create and download zip file whole check it.

<?php
// Create ZipArchive object
$zip = new ZipArchive();

// Create the zip file name
$filename="myzip.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE )!=TRUE) 
{
	exit("cannot open <$archive_file_name>\n");
}

// Create the folder name
$dir = 'myfolder/';

createZip($zip,$dir);

// Create zip
function createZip($zip,$dir)
{
	if (is_dir($dir))
	{
	  	if ($dh = opendir($dir))
	  	{
	   		while (($file = readdir($dh)) !== false)
	   		{
	    		// If file
	    		if (is_file($dir.$file)) 
	    		{
	     			if($file != '' && $file != '.' && $file != '..')
	     			{
	      				$zip->addFile($dir.$file);
	     			}
	    		}
	    		else
	    		{
	     			// If directory
	     			if(is_dir($dir.$file) )
	     			{
	      				if($file != '' && $file != '.' && $file != '..')
	      				{
	       					// Add empty directory
	       					$zip->addEmptyDir($dir.$file);
	       					$folder = $dir.$file.'/';
	 
	       					// Read data of the folder
	       					createZip($zip,$folder);
	      				}
	     			}
	    		}
	   		}
	   		closedir($dh);
	  	}
	}
}

if(file_exists($filename))
{
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
	header("Content-type: application/zip"); 
	header("Content-Disposition: attachment; filename=$filename"); 

	readfile($filename); 

	// delete file
	unlink($filename);
}

?>

Basic Details

  • The above function createZip($zip,$dir) accept object and path of the directory as a two parameter. It will read all files and folders from the path and add in the zip archive file.
  • $zip = new ZipArchive();
  • $dir = 'myfolder/';