How to Create Zip Files using PHP ZipArchive and Download

by Vincy. Last modified on September 12th, 2022.

Creating a zip from a folder full of files can be done in PHP using the ZipArchive class. This class instance creates a handle to read or write files to a compressed archive.

This class includes several properties and methods to zip file archives.

In this article, we will see an example of,

  1. How to create a zip archive file.
  2. How to download the compressed zip file.

If you want to know how to compress more than one image in PHP image compression refer to this earlier article.

How to create a zip archive file

This file parses the input directory and compresses its files into a zip file. It proceeds with the following steps to create the zip file of a directory.

  1. Create a PHP ZipArchive class instance.
  2. Open a zip file archive with the instance. It accepts the output zip file name and the mode to open the archive.
  3. Apply a recursive parsing in the input directory.
  4. If the directory includes a file, then it adds to the zip archive usingĀ addFile().

It handles the use cases of getting the possibilities of being unable to read or archive the directory. Once the zip is created, it displays a message to the browser.

create-zip-file.php

<?php
// Important: You should have read and write permissions to read
// the folder and write the zip file
$zipArchive = new ZipArchive();
$zipFile = "./example-zip-file.zip";
if ($zipArchive->open($zipFile, ZipArchive::CREATE) !== TRUE) {
    exit("Unable to open file.");
}
$folder = 'example-folder/';
createZip($zipArchive, $folder);
$zipArchive->close();
echo 'Zip file created.';

function createZip($zipArchive, $folder)
{
    if (is_dir($folder)) {
        if ($f = opendir($folder)) {
            while (($file = readdir($f)) !== false) {
                if (is_file($folder . $file)) {
                    if ($file != '' && $file != '.' && $file != '..') {
                        $zipArchive->addFile($folder . $file);
                    }
                } else {
                    if (is_dir($folder . $file)) {
                        if ($file != '' && $file != '.' && $file != '..') {
                            $zipArchive->addEmptyDir($folder . $file);
                            $folder = $folder . $file . '/';
                            createZip($zipArchive, $folder);
                        }
                    }
                }
            }
            closedir($f);
        } else {
            exit("Unable to open directory " . $folder);
        }
    } else {
        exit($folder . " is not a directory.");
    }
}
?>

Output

//If succeeded it returns 
Zip file created.

//If failed it returns 
Unable to open directory example-folder.
[or]
"example-folder is not a director.

php create zip

How to download the compressed zip file

In the last step, the zip file is created using the PHP ZipArchive class. That zip file can be downloaded by using the PHP code below.

It follows the below steps to download the zip file created.

  1. Get the absolute path of the zip file.
  2. Set the header parameters like,
    • Content length.
    • Content type.
    • Content encoding, and more.

download-zip-file.php

<?php
$filename = "example-zip-file.zip";
if (file_exists($filename)) {
    // adjust the below absolute file path according to the folder you have downloaded
    // the zip file
    // I have downloaded the zip file to the current folder
    $absoluteFilePath = __DIR__ . '/' . $filename;
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    // content-type has to be defined according to the file extension (filetype)
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($absoluteFilePath));
    readfile($absoluteFilePath);
    exit();
}
?>

This file just has the links to trigger the function to create a zip file containing the compressed archive of the directory. Then, the action to download the output zip archive is called.

index.php

<div class='container'>
    <h2>Create and Download Zip file using PHP</h2>
    <p>
        <a href="create-zip-file.php">Create Zip File</a>
    </p>
    <p>
        <a href="download-zip-file.php">Download Zip File</a>
    </p>
</div>

Some methods of PHP ZipArchive class

We can do more operations by using the methods and properties of the PHP ZipArchive class. This list of methods is provided by this PHP class.

  1. count() – used to get the number of files in the zip archive file.
  2. extractTo() – extracts the archive content.
  3. renameIndex() – rename a particular archive entry by index.
  4. replaceFile() – replace a file in the zip archive with a new file by specifying a new path.

ZipArchive methods used in this example

Some of the methods are used in this example listed below. These are frequently used methods of this class to work with this.

  1. open() – Open a zip archive file by specifying the .zip file name.
  2. addFile() – To add a file from the input directory to the zip archive.
  3. addEmptyDir() – adds an empty directory into the archive to load the subdirectory file of the input directory.
  4. close() – closes the active ZipArchive with the reference of the handle.

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page