Home >Backend Development >PHP Tutorial >How to Create and Download a Multi-File ZIP Archive in PHP?
Creating ZIP Archives with Multiple Files in PHP
To download multiple files as a single ZIP archive using PHP, we can leverage the ZipArchive class.
Creating the ZIP Archive:
$files = array('readme.txt', 'test.html', 'image.gif'); $zipname = 'file.zip'; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE); foreach ($files as $file) { $zip->addFile($file); } $zip->close();
This code creates a ZIP archive named 'file.zip' and adds the specified files to it.
Streaming the ZIP Archive for Download:
header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname);
These headers prepare the browser to display a download prompt and set the appropriate file name and size. By reading the ZIP archive file and streaming its contents, the browser can download it.
Additional Notes:
The above is the detailed content of How to Create and Download a Multi-File ZIP Archive in PHP?. For more information, please follow other related articles on the PHP Chinese website!