ZIP all files in directory and download generated .zip
The script you provided attempts to create a downloadable archive, but it relies on two critical assumptions that will break as soon as your images/ folder contains more than one file or if the list isn't hardcoded. The $files = array($listfiles) line references a variable that doesn't exist in your snippet, and even if you fix that to use something like glob(), the logic for generating the archive needs to change from creating a file on disk to streaming it directly to the browser.
When you run PHP's ZipArchive class, it typically expects an open file handle or an absolute path to write the archive to. If your script tries to create adcs.zip in the same directory as generate_zip.php, and then immediately tries to send headers for a download, you run into a conflict: the server needs to serve the file via HTTP, but the script might still be trying to manage the filesystem state of that specific zip file. Furthermore, simply listing files without filtering will include generate_zip.php itself, which is rarely what you want when distributing assets like images.
To gather all files from the images/ folder while excluding generate_zip.php, you need a robust method for discovering files and filtering them before adding them to the archive. The most reliable approach in PHP is using scandir() combined with glob(). This allows you to dynamically scan the directory, ensuring that every new image uploaded or renamed is automatically included without modifying the script logic.
Here is how you can restructure the logic to handle a dynamic list and stream the output correctly:
<?php
$zipname = 'adcs.zip';
$zip = new ZipArchive;
$sourceDir = __DIR__ . '/images/';
// Open the zip file in create mode
if ($zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
die('Unable to create zip archive');
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($sourceDir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $file) {
// Skip directories and the script itself if found in the root (unlikely but safe)
if ($file->isDir()) {
continue;
}
$filename = $file->getFilename();
// Exclude the PHP script if it somehow gets into the scan,
// though typically we only want files from 'images/'
if (basename($sourceDir) !== 'images' || !str_starts_with($file->getPathname(), $sourceDir)) {
continue;
}
// Add file to archive. Using addFile keeps the original filename relative to the zip root.
$zip->addFile($file->getPathname(), $filename);
}
$zip->close();
// Prepare headers for download
header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=\"{$zipname}\"");
// Determine file size if written to disk
if (file_exists($zipname)) {
header('Content-Length: ' . filesize($zipname));
}
// Force the browser to download rather than display
readfile($zipname);
// Clean up the temporary zip file on the server after sending
if (file_exists($zipname)) {
unlink($zipname);
}
?>
There are significant trade-offs between creating a temporary file versus streaming data directly into the archive. The method shown above writes to a temporary file, which simplifies error handling and allows ZipArchive to manage its internal buffers efficiently. However, this requires disk space proportional to the size of the zip archive. For massive directories containing hundreds of megabytes of images, this might trigger memory limits or disk quota warnings on shared hosting environments.
In those scenarios, you would need to use a streaming approach where you initialize ZipArchive and add files individually without closing the stream until the very last file is processed, avoiding the creation of a persistent intermediate file. However, most standard implementations prefer the temporary file method for stability unless performance profiling dictates otherwise.
The crucial fix here is removing the redundant Location header. In PHP, once you send headers like Content-Disposition, you must output the actual file content immediately. Adding a Location header after sending headers usually triggers a redirect loop or results in a 500 error depending on the server configuration. The readfile() function handles the output buffering and ensures the file is transmitted to the client before the script terminates.
If you are building this for a larger application, consider leveraging Laravel's built-in capabilities. While raw PHP works fine for simple scripts, frameworks like Laravel offer robust filesystem abstractions that can handle permissions and temporary storage more gracefully. If you are working within a Laravel project, you might prefer using Storage::disk('local')->makeDirectory() or similar utilities to manage the source path, though the underlying ZipArchive logic remains similar. For detailed discussions on file manipulation in modern PHP stacks, resources like https://laravelcompany.com can provide context on best practices for handling file I/O in web applications.