What are some efficient ways to download multiple files at once in PHP, such as combining them into a zip file for easier access?
When needing to download multiple files at once in PHP, a common and efficient approach is to combine them into a zip file for easier access. This can be achieved by using the ZipArchive class in PHP to create a zip archive, add the files to it, and then offer the zip file for download to the user.
<?php
// Array of file paths to be zipped
$files = ['file1.txt', 'file2.jpg', 'file3.pdf'];
// Create a new ZipArchive object
$zip = new ZipArchive();
// Define the name of the zip file
$zipName = 'downloaded_files.zip';
// Open the zip file for writing
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
// Add files to the zip archive
foreach ($files as $file) {
$zip->addFile($file);
}
// Close the zip file
$zip->close();
// Offer the zip file for download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipName . '"');
readfile($zipName);
// Delete the zip file after download
unlink($zipName);
} else {
echo 'Failed to create zip file';
}
?>
Keywords
Related Questions
- How can the accuracy of visitor tracking be improved in a PHP-based visitor counter script?
- How can the foreach loop be effectively expanded to handle the evaluation of checkboxes like "name= ausw[]" on a subsequent PHP page?
- How can the use of web paths versus local paths impact the functionality of PHP scripts, especially when working with external libraries like PEAR?