Search code examples
phparrayszipphp-ziparchive

ZipArchive PHP: Close() returns false with no error message


I'm trying to create a zip file with directory tree based on array strutucture.

I already use this answer when I need to create a zip file from a directory tree, but in this case all the files are in the same directory and the directory tree is based on other data from database.

I've checked that all files are in the correct path and that the foreach loops are working. The error is happening with $zip->close.

That's the code (the original array has many entries in each level):

$zip_array = array( 'Level 1' =>  array( 
                    'Level 2' => array ( 
                            'file 1' => '/var/www/html/pdf/683026577.pdf',
                            'file 2' => '/var/www/html/pdf/683026578.pdf'
                            'file 3' => '/var/www/html/pdf/683026579.pdf'
                            )
                    )
        );
$destination = 'testzip.zip';
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        echo "fail";
    }
foreach ($zip_array as $key => $level2){
    $lev1 = '/'.$key.'/';
    $zip->addEmptyDir($lev1);
    foreach ($level2 as $key => $level3){
        $lev2 = $level1 . $level2.'/';
        $zip->addEmptyDir(lev2);
        foreach ($level3 as $key => $file){
            $lev3 = $lev2 . $key.'.pdf';
                    $zip->addFile($file, $lev3); 
        }
    }
}
$close = $zip->close();
if ($close){
    echo "Ok"
}else{
    echo "Fail";
}

Solution

  • Error handling in PHP is a little strange sometimes. If the close() function returned false, there was an error, but it won't explicitly tell you what the error was. Use ZipArchive::getStatusString to get the status of your $zip object. That will tell you exactly what the error was, and you can then take steps to fix the problem.

    This pattern of checking for an error status when false is returned is fairly common in PHP - especially with older code that may have been written before PHP had good exception handling support.