ZIP file not being created, but no error gets triggered
Make sure that:
- All files added actually exist (check each file with
file_exists()
andis_readable()
before calling$zip->addFile()
). - When iterating folder, exclude
.
and..
. - There is at least one file to zip (
$zip['numFiles'] > 0
). - Calling
$zip->close()
returnsTRUE
.
Sounds like you have a permission issue, either with writing to the zip file, or reading the files it is zipping.
I would use a combination of file_exists
, is_readable
, and is_writable
to figure out which of these is causing the problem.
function zip_dir($source, $target){
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);
$zip = new \ZipArchive();
if($zip->open($target, \ZipArchive::CREATE) !== true)
exit('cannot create zip');
foreach($iterator as $file){
if (!file_exists($file)) { die($file.' does not exist'); }
if (!is_readable($file)) { die($file.' not readable'); }
$zip->addFile($file);
print $file . '<br>';
}
$zip->close();
return $target;
}
if (!is_writable(__DIR__)) { die('directory not writable'); }
zip_dir(__DIR__ . '/test/', __DIR__ . '/testarchive.zip');
Two Comments From php.net
If you're adding multiple files to a zip and your $zip->close()
call is returning FALSE, ensure that all the files you added actually exist. Apparently $zip->addFile()
returns TRUE even if the file doesn't actually exist. It's a good idea to check each file with file_exists()
or is_readable()
before calling $zip->addFile()
on it.
and
Don't forget to check the zip isn't empty, folks - otherwise the zip won't be created at all, and the server will issue no warning!