PHP Zip file download error when opening
Solution 1:
Try to open the zip file with a text editor. This way you can check if were is a php error in your code (during the compression step).
Solution 2:
Check that the web server user has write permission to the folder where you're creating the ZIP file. Notwithstanding the documentation, ZipArchive::open()
will fail silently and return true
(i.e. success) if it cannot create the ZIP file. Further, ZipArchive::addFile()
will seemingly add as many files as you wish to this non-existent archive, also without reporting an error. The first point at which an error appears is when ZipArchive::close() returns `false'. No error messages appear in the error logs, either.
Readfile()
will report an error to the logs and fail, so the result is a zero-length ZIP file on your local hard disk.
The reason seems to be that the ZipArchive class is only assembling a list of files in memory until it's closed, at which point it assembles all the files into the Zip file. If this can't be done then ZipArchive::close()
returns false
.
Note: if the zip file is empty, it might not be created at all! Your download will proceed, but readfile()
will fail and you'll get a zero-length ZIP file downloaded.
What to do?
Add a little error checking to your code to report some of this:
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// Add your files here
if ($zip->close() === false) {
exit("Error creating ZIP file");
};
//download file from temporary file on server as '$filename.zip'
if (file_exists($zipname)) {
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$filename.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
} else {
exit("Could not find Zip file to download");
}