Skip to Content
Course content

127: ZipArchive for Compression

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably hit a point in your project where you're dealing with too many individual files—maybe it's a set of user-uploaded documents or a bunch of daily logs—and you realize that sending 50 separate files over the wire or storing them loosely is a nightmare. That's where the ZipArchive class comes in. It's the standard way in PHP to bundle files together and compress them.

How do I actually create a zip file and put some files in it?

The most important thing to remember is that ZipArchive doesn't just "save" a file instantly. You open a handle to a zip file, add your items, and then you must call close(). If you forget close(), the file won't actually be written to disk, and you'll be left wondering why your zip folder is 0 bytes.

$zip = new ZipArchive();
$filename = "user_export_123.zip";

if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    // Add a specific file: addFile(path_on_disk, name_inside_zip)
    $zip->addFile('exports/report.pdf', 'report.pdf');
    $zip->addFile('exports/data.csv', 'data.csv');
    
    // You can even add strings as files if you don't have a physical file on disk
    $zip->addFromString('readme.txt', 'This export was generated on ' . date('Y-m-d'));
    
    $zip->close();
    echo "Zip created successfully!";
} else {
    echo "Failed to create zip.";
}

Is there a way to zip an entire folder without adding every file one by one?

Manually calling addFile() is fine for two or three items, but if you're zipping a directory of 500 images, you need a loop. PHP doesn't have a "zipFolder()" method out of the box, so we combine ZipArchive with a RecursiveIteratorIterator. I use this pattern all the time for backup scripts.

$zip = new ZipArchive();
$sourceFolder = 'uploads/user_assets/';
$destFile = 'backup.zip';

if ($zip->open($destFile, ZipArchive::CREATE) === TRUE) {
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($sourceFolder),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {
        // Skip directories (they are added automatically when files are added)
        if (!$file->isDir()) {
            // Get the real path to the file
            $filePath = $file->getRealPath();
            
            // We want the path inside the zip to be relative to the source folder
            // Otherwise, the zip will contain the full absolute path of your server
            $relativePath = substr($filePath, strlen($sourceFolder));
            
            $zip->addFile($filePath, $relativePath);
        }
    }
    $zip->close();
}

How do I extract a zip file back into a folder?

Unzipping is significantly simpler than zipping. You don't have to loop through files; you just tell PHP where the zip is and where you want the contents to land. One quick tip: make sure the destination folder has the correct write permissions, or extractTo() will fail silently or throw a warning depending on your error settings.

$zip = new ZipArchive();
$zipFile = 'incoming_data.zip';
$extractPath = 'temp/extracted_files/';

if ($zip->open($zipFile) === TRUE) {
    // This extracts everything in the archive to the specified directory
    $zip->extractTo($extractPath);
    $zip->close();
    echo "Files extracted to $extractPath";
} else {
    echo "Could not open the zip file.";
}



📋 Practical Task

Build a Timestamped Log Archiver

Create a script that automates the archiving of a logs directory. Your script should perform the following steps:

  • Define a source directory named logs/ (create a few dummy .txt files in there first).
  • Generate a filename for the zip archive that includes the current date and time (e.g., logs_archive_2023-10-27_1430.zip).
  • Use a RecursiveIteratorIterator to find all files within the logs/ folder and add them to the archive.
  • Ensure the files inside the zip maintain their relative structure (don't include the full server path).
  • After the zip is successfully closed, use unlink() to delete the original dummy text files from the logs/ folder to simulate a "cleanup" process.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.