Creating a ZIP Archive from Multiple Files in PHP
Question: How can I download multiple files as a ZIP archive using PHP?
Solution:
To achieve this, you can leverage PHP's ZipArchive class. Here's how you can proceed:
Create a ZIP Archive:
$files = array('readme.txt', 'test.html', 'image.gif'); $zipname = 'file.zip'; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE);
Add Files to the ZIP Archive:
foreach ($files as $file) { $zip->addFile($file); }
Close the ZIP Archive:
$zip->close();
Stream the ZIP Archive to the Client:
header('Content-Type: application/zip'); header('Content-disposition: attachment; filename="'.$zipname.'"'); header('Content-Length: ' . filesize($zipname)); readfile($zipname);
The first line in the streaming section specifies the Content-Type as a ZIP archive. The second line instructs the browser to display a download box for the user and assigns the filename file.zip. The third line calculates and sets the Content-Length header for older browsers that may encounter issues without knowing the file size in advance.
The above is the detailed content of How to Create and Download a ZIP Archive of Multiple Files Using PHP?. For more information, please follow other related articles on the PHP Chinese website!