Archimedix Archimedix - 2 months ago 26
PHP Question

ZipArchive::getStatusString(): Invalid or uninitialized Zip object

The following code will fail to create a ZIP file in PHP 5.6.12 and will also fail to print out the ZIP error message, instead displaying the error / warning

Warning: ZipArchive::getStatusString(): Invalid or uninitialized Zip object in /tmp/x.php on line 9


But why? This once worked in PHP 5.4.



<?php

// TODO: Check for errors
$tempPath = tempnam('/tmp', 'ztmp');

$zip = new ZipArchive();
$res = $zip->open($tempPath, ZipArchive::OVERWRITE | ZipArchive::CREATE | ZipArchive::EXCL);

if ( $res !== true )
die($zip->getStatusString()."\n");

Answer

It looks like the semantics have changed somewhat; it is unclear whether it is deliberate or a bug.

Anyways, the problem is that we have an empty file which is not a valid ZIP but which is being opened nonetheless and not initialized properly even though we requested the file to be overwritten.

So the workaround or fix is to delete the existing file and then recreate it:

<?php

$tempPath = tempnam('/tmp', 'ztmp');

// Delete first
@unlink($tempPath);

$zip = new ZipArchive();
$res = $zip->open($tempPath, ZipArchive::OVERWRITE | ZipArchive::CREATE | ZipArchive::EXCL);

if ( $res !== true )
    die($zip->getStatusString()."\n");