In web development, there are scenarios where you need to provide multiple files for download in a single, compressed package. PHP offers a convenient solution for this task using the ZipArchive class.
To create a ZIP archive, follow these steps:
$zipname = 'file.zip'; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE);
Here, $zip represents the ZIP archive, and $zipname is the desired filename.
Once the ZIP archive is created, you can add individual files to it:
foreach ($files as $file) { $zip->addFile($file); }
Replace $files with an array containing the file paths or names.
After adding all the necessary files, close the archive:
$zip->close();
Now, stream the archive to the client for download:
header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname);
This code forces the browser to prompt a download box and designates the filename. The file size is specified to resolve compatibility issues in some browsers.
With these steps, you can easily create and download multiple files as a single ZIP archive using PHP.
The above is the detailed content of How to Create a Downloadable ZIP Archive of Multiple Files Using PHP?. For more information, please follow other related articles on the PHP Chinese website!