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


Contents

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

 


 

1. HTML

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' />
 </form>
</div>

 


 

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

<?php 
// Create ZIP file
if(isset($_POST['create'])){
 $zip = new ZipArchive();
 $filename = "./myzipfile.zip";

 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 != '..'){
          $zip->addFile($dir.$file);
       }
 
     }
     closedir($dh);
   }
 }
 $zip->close();
}

// Download Created Zip file
if(isset($_POST['download'])){
 
 $filename = "myzipfile.zip";

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

    flush();
    readfile($filename);
    
    // delete file
    unlink($filename);

 }
}
?>

 

3. CSS

.container{
 margin: 0 auto;
 width: 50%;
 text-align: center;
}

input[type=submit]{
 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 *