How can PHP be used to automate the creation of ZIP archives for download purposes?
To automate the creation of ZIP archives for download purposes using PHP, you can use the ZipArchive class. This class allows you to create, open, and extract ZIP archives easily. You can add files to the archive, set compression levels, and create directories within the archive. Finally, you can send the ZIP archive to the user for download.
// Create a new ZIP archive
$zip = new ZipArchive();
$zipName = 'example.zip';
if ($zip->open($zipName, ZipArchive::CREATE) === TRUE) {
// Add files to the archive
$zip->addFile('file1.txt');
$zip->addFile('file2.txt');
// Close the archive
$zip->close();
// Set headers to force download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zipName).'"');
header('Content-Length: ' . filesize($zipName));
// Send the ZIP archive to the user
readfile($zipName);
// Delete the temporary ZIP archive file
unlink($zipName);
} else {
echo 'Failed to create ZIP archive';
}