How to create a ZIP file using PHP.

In this guide, we will show you how to create a ZIP file using PHP.

We will also show you how to force the browser to download it as an attachment.

Creating ZIP archives using PHP.

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/example.zip';

//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(
    '/home/data/image.png',
    '/home/data/test.jpg'
);

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

//Finally, close the active archive.
$zipArchive->close();

//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.
readfile($zipFilePath);
exit;

An explanation of the code above:

  1. Firstly, we create a ZipArchive object called $zipArchive. Note that this class is only available in PHP versions 5.2.0 and above.
  2. On the next line, we specify the full path of the location where we want to save our Zip Archive. This path should also include the filename and the .zip file extension.
  3. We create a new Zip archive by using the ZipArchive::open function. The ZipArchive::CREATE flag in the second parameter tells the ZipArchive object that it should create the file if it doesn’t already exist. If you want to overwrite an existing Zip file, then you should use the ZipArchive::OVERWRITE flag instead.
  4. After that, we create a PHP array and add the full path of each file that we want to add to our archive.
  5. We loop through our array of file paths and add them to the archive by using the ZipArchive::addFile function.
  6. Finally, we use the ZipArchive::close function to close off the archive and save the ZIP file.
  7. After creating the file, we force the browser to download it as an attachment. We do 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 further information about this part of the code, then you can read our article on forcing a PDF file to download.

And that’s it! Done.