How To Create And Download Zip File In PHP

By : phpicoder Created : March 5, 2021

Today, i create a smole php script to creat and download zip 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 create and download zip file in php example using ZipArchive() php class.

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.

Create Folder :

First create folder in create zip file, like /folderName/

$dir = 'folderName/';

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 = 'folderName/';

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 = 'folderName/';
createZip($zip,$dir);

I hope it can help you for create and download zip file in php tutorial...