The zip file is not created, but the error does not start

I am using ZipArchive:

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){ $zip->addFile($file); print $file . '<br>'; } $zip->close(); return $target; } zip_dir(__DIR__ . '/test/', __DIR__ . '/testarchive.zip'); 

I see a list of files, but in the end I can’t find the zip file that needs to be created. And I have no errors / exceptions from ZipArchive ...

edit:

I added print $zip->getStatusString(); after $zip->close();

and it prints: Cannot open file: Permission denied. "What does this mean? I know for sure that every directory is writable, bc I can create new files with PHP inside them ...

edit 2:

 if(is_writable(dirname($target))) print 'target dir is writable...'; 

it prints this, so the directory is writable. I feel like I'm in the twilight zone ...

+8
file php zip ziparchive
source share
3 answers

Two comments from php.net

If you add multiple files to zip, and your call to $ zip-> close () returns FALSE, make sure that all the files you added really exist. Obviously, $ zip-> addFile () returns TRUE, even if the file does not actually exist. It is recommended to check each file with file_exists () or is_readable () before calling $ zip-> addFile () on it.

and

Remember to check that the zip is not empty, people - otherwise the zip will not be created at all, and the server will not give a warning!

+7
source share

It looks like you have a resolution problem, either with writing to a zip file, or with reading the files that it clamps.

I would use a combination of file_exists , is_readable and is_writable to figure out which one 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'); 
+6
source share

Make sure that:

  • All added files really exist (check each file with file_exists() and is_readable() before calling $zip->addFile() ).
  • When iterating, exclude folders . and ..
  • There is at least one file for zip ( $zip['numFiles'] > 0 ).
  • Calling $zip->close() returns TRUE .
+1
source share

All Articles