Create a ZIP file using PHP.

In this guide, I will show you how to create a ZIP file using PHP. After creating our ZIP file, we will then force the browser to download it as an attachment.


Take a look at the following PHP example, which uses the ZipArchive class:

//Create an object from the ZipArchive class.
$zipArchive = new ZipArchive();

//The full path to where we want to save the zip file.
$zipFilePath = '/home/data/';

//Call the open function.
$status = $zipArchive->open($zipFilePath,  ZipArchive::CREATE);

//An array of files that we want to add to our zip archive.
//You should list the full path to each file.
$filesToAdd = array(

//Add our files to the archive by using the addFile function.
foreach($filesToAdd as $fileToAdd){
    //Add the file in question using the addFile function.

//Finally, close the active archive.

//Get the basename of the zip file.
$zipBaseName = basename($zipFilePath);

//Set the Content-Type, Content-Disposition and Content-Length headers.
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$zipBaseName");
header("Content-Length: " . filesize($zipFilePath));

//Read the file data and exit the script.

An explanation of the code above:

  1. We instantiated the ZipArchive class and created an object called $zipArchive. Note that this class is only available in PHP versions 5.2.0 and above.
  2. We specified the full path to where we want to save our Zip Archive. This path should also include the filename and the .zip file extension.
  3. Using the ZipArchive::open function, we created a new Zip archive. The ZipArchive::CREATE flag that we passed in as a second parameter tells the ZipArchive object that it should create the file if it doesn’t already exist. If you’re OK with overwriting an existing Zip file, then you should the ZipArchive::OVERWRITE flag instead.
  4. We created a PHP array and added the full path to each file that we want to add to our archive.
  5. We looped through our array of file paths and added them to the archive by using the ZipArchive::addFile function.
  6. The ZipArchive::close function is then used to close off the archive and save the ZIP file.
  7. After the file has been created, we forced the browser to download it as an attachment. We did this by sending the correct Content-Disposition header. We also dynamically calculated the Content-Length header using the filesize function. If you are looking for a more in-depth explanation on this part of the code, then you can read my recent article on forcing a PDF file to download.

Hopefully, you found this tutorial to be useful!