Download multiple files as a zip-file using php
Archiving multiple files into a single downloadable package is a common requirement in web applications, from bulk data exports to delivering complex assets to clients. While many frameworks provide helpers for this task, understanding the underlying mechanics ensures you handle memory correctly and avoid security pitfalls. The most straightforward approach in PHP relies on the ZipArchive class, which offers a programmatic way to construct archives without needing external dependencies like PECL extensions or system binaries.
The ZipArchive class operates synchronously, meaning it processes files sequentially. To create a downloadable zip file directly to the browser, you must first instantiate the archive object and set the compression level. Compression levels range from 0 (no compression) to 9 (maximum compression). For large datasets, level 6 usually strikes the best balance between speed and file size reduction without significantly increasing memory usage.
$zip = new ZipArchive();
if ($zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
throw new RuntimeException('Unable to create archive');
}
$zip->setCompressionMethod(ZIPARCHIVE_COMPRESSION_DEFLATE);
$zip->setCompressionLevel(6);
Once the archive is open, you add each file using the addFile method. This method requires two arguments: the source path and the destination path within the zip. The destination path becomes the filename inside the archive, which allows you to structure the internal directory layout regardless of where the files reside on your server. If you are archiving a directory, you can pass the directory path as the source; PHP will automatically add all contained files and subdirectories, preserving the relative structure.
// Adding individual files with custom names inside the zip
$zip->addFile($sourcePath . '/config.json', 'config.json');
$zip->addFile($sourcePath . '/readme.md', 'readme.md');
// Adding an entire directory and its contents
$zip->addDir($sourcePath . '/assets', 'assets');
After populating the archive, you must save it. The close method finalizes the file on disk. However, saving to disk first introduces a latency issue if you want an instant download. A more efficient pattern involves writing the zip directly to the output buffer using open($filename, ZipArchive::CREATE) followed by close(), but this still touches the filesystem. To achieve a true stream-based download without touching disk (beyond temporary storage for the final file), you can use ZipArchive in combination with PHP's output buffering, though ZipArchive itself does not natively support streaming creation in a way that avoids writing the final chunk to disk before sending headers.
To trigger the download, you need to set the appropriate HTTP headers. The Content-Type should be application/zip, and the Content-Disposition header must use an inline filename attribute with proper URL encoding. This tells the browser to save the file rather than preview it.
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false);
header('Content-Transfer-Encoding: binary');
$zip->open($filename, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// ... add files logic here ...
$zip->close();
flush();
readfile($filename);
A critical trade-off with ZipArchive is memory consumption. Since the entire archive is built in memory before writing to disk (or stream), adding thousands of large files can exhaust the memory_limit. If you encounter this issue, consider chunking the file addition or switching to a streaming solution like php-zip-stream if available for your environment. Always ensure the destination path is validated to prevent directory traversal vulnerabilities, even when using relative paths inside the archive.
