How can PHP be used to automate the process of creating and offering a ZIP file for download to users?
To automate the process of creating and offering a ZIP file for download to users using PHP, you can use the ZipArchive class to create a ZIP file containing the desired files, and then use header() function to set the appropriate headers for downloading the ZIP file.
// Create a new ZIP file
$zip = new ZipArchive();
$zipFileName = 'example.zip';
if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
$zip->addFile('file1.txt', 'file1.txt');
$zip->addFile('file2.txt', 'file2.txt');
$zip->close();
}
// Offer the ZIP file for download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
header('Content-Length: ' . filesize($zipFileName));
readfile($zipFileName);
Keywords
Related Questions
- What are some best practices for integrating external links in PHP code?
- How can PHP beginners ensure their code is more readable and maintainable when working with file handling functions like fopen and fwrite?
- Are there any potential issues with using the nl2br function in PHP for converting line breaks?