What is the best way to collect and download multiple files in PHP?
When needing to collect and download multiple files in PHP, one way to achieve this is by creating a zip archive containing all the files and then prompting the user to download the zip file. This approach simplifies the process for the user by providing a single download link for all the files.
<?php
// Array of file paths to be included in the zip archive
$files = array('file1.txt', 'file2.pdf', 'file3.jpg');
// Create a new zip archive
$zip = new ZipArchive();
$zipName = 'files.zip';
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
// Add files to the zip archive
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="' . $zipName . '"');
readfile($zipName);
// Delete the zip file after download
unlink($zipName);
} else {
echo 'Failed to create zip archive';
}
?>
Related Questions
- What is the best practice for filtering out a specific character in an array and displaying it as a title in PHP?
- How can the issue of octal numbers affecting PHP functions be avoided?
- What are some common libraries or tools recommended for beginners to use when creating a signature generator in PHP?