How to create and download a Zip file with PHP

PHP provides ZipArchive Class which allows us to create Zip file. For this, we need to create Object of that class and use addFile method which takes file name for adding the file to zip archive file.

When it’s required?

Programmatically Zip creation mainly requires when preparing the group of file and folders for downloading.

In the tutorial, demonstration I will read all files from a folder and add those files for Zipping.

How To Create And Download A Zip File with PHP


  1. HTML
  2. PHP
  3. CSS
  4. Conclusion




Creating a <form> which have two button elements, one for Create Zip and another for Download.

Completed Code

<div class='container'>
 <h1>Create and Download Zip file using PHP</h1>
 <form method='post' action=''>
  <input type='submit' name='create' value='Create Zip' />&nbsp;
  <input type='submit' name='download' value='Download' />



2. PHP

I have created includes folder within the project where I stored some files.

Create Zip

Creating ZipArchive Class object for Zip file creation. Read all files from includes folder and add it to $zip object using addFile() method.

Download Zip

Download the zip file which has been created using create button. After download remove the file from the project directory.

Completed Code

// Create ZIP file
 $zip = new ZipArchive();
 $filename = "./";

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

 $dir = 'includes/';
 if (is_dir($dir)){

   if ($dh = opendir($dir)){
     while (($file = readdir($dh)) !== false){

       if($file != '' && $file != '.' && $file != '..'){

// Download Created Zip file
 $filename = "";

 if (file_exists($filename)) {
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.basename($filename).'"');
    header('Content-Length: ' . filesize($filename));

    // delete file



3. CSS

 margin: 0 auto;
 width: 50%;
 text-align: center;

 border: 0px;
 padding: 7px 15px;
 font-size: 16px;
 background-color: #00a1a1;
 color: white;
 font-weight: bold;


4. Conclusion

If you are allowing the users to download the files one by one here you can use the above PHP script to group together all files in the form of Zip and allow it for download.

Spread the love

Related Post

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *