How can PHP be used to create a zip function for downloading multiple files at once?
When downloading multiple files at once, it is more efficient to create a zip archive containing all the files rather than downloading each file individually. This can be achieved using PHP's ZipArchive class to create a zip file on the server and then prompt the user to download it. By looping through the files to be included in the zip archive and adding them to the archive, we can provide a single download link for all the files.
<?php
// Array of files to be zipped
$files = array('file1.txt', 'file2.jpg', 'file3.pdf');
// Create a zip file
$zip = new ZipArchive();
$zipname = 'download.zip';
$zip->open($zipname, ZipArchive::CREATE);
// Add files to the zip
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
// Prompt user to download the zip file
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zipname).'"');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// Delete the zip file after download
unlink($zipname);
?>
Related Questions
- What are the best practices for integrating JavaScript and PHP to handle client-side and server-side operations efficiently?
- What are the advantages of using integer data types for sorting in MySQL when using PHP?
- Are there any best practices for securely storing and verifying passwords in a PHP login system?