Pragmatism in the real world

Creating a zip file with PHP's ZipArchive

I recently had a requirement to create a zip file from a number of files created within my application.

As it has been years since I last had this problem, I had a look around and discovered that PHP 5.2 has the ZipArchive class that makes this easy. ZipArchive is fully featured, but as I just wanted to create a simple zip file, all that I needed to do was:

$zip = new ZipArchive();
$zip->open('path/to/zipfile.zip', ZipArchive::CREATE);

$zip->addFile('some-file.pdf', 'subdir/filename.pdf');
$zip->addFile('another-file.xlxs', 'filename.xlxs');

$zip->close();

Note that I can set the filename and any subdirectories within the zip file completely independently of the name and location of the file that I am adding which is useful.

The file ‘zipfile.zip’ is now ready for downloading which currently I do using:

// send $filename to browser
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filename);
$size = filesize($filename);
$name = basename($filename);

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    // cache settings for IE6 on HTTPS
    header('Cache-Control: max-age=120');
    header('Pragma: public');
} else {
    header('Cache-Control: private, max-age=120, must-revalidate');
    header("Pragma: no-cache");
}
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // long ago
header("Content-Type: $mimeType");
header('Content-Disposition: attachment; filename="' . $name . '";');
header("Accept-Ranges: bytes");
header('Content-Length: ' . filesize($filename));

print readfile($filename);
exit;

Now, the next time I need to do this, I’ll remember what I did!

One thought on “Creating a zip file with PHP's ZipArchive

Comments are closed.