Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 7 ZipArchive::OVERWRITE not working

Tags:

php

php-7

This might be a bug in the new release... or maybe something has changed the behavior of ZipArchive and my code is just old, however, the following code works when the CREATE flag is used, but breaks when the OVERWRITE flag is used. It worked fine under PHP 5.6, but under PHP 7.0 I get the following error:

    Warning: ZipArchive::close(): Invalid or uninitialized Zip object

Original code:

foreach( glob($sourcedir.'*.[zZ][iI][pP]') as $zippath)
{
    // create daily zip file
    $zipname = preg_replace('~'.$sourcedir.'~','',$zippath);
    $zipname2 = preg_replace('~\.zip~','',$zipname);

    $zip = new ZipArchive();
    $ret = $zip->open($xmlzip.$zipname2.'_contact_xml.zip', ZipArchive::OVERWRITE);

    // move xml files to daily zip file created above
    if ($ret !== TRUE) {
        printf('Failed with code %d', $ret);
    } else {

      foreach(glob($source_file_path.'*.[xX][mM][lL]') as $xmlpath){
         $zip->addFile($xmlpath, preg_replace('~'.$source_file_path.'~','',$xmlpath));
      }

    }

    $zip->close();
}

Any ideas?

like image 482
photocode Avatar asked Aug 29 '16 05:08

photocode


1 Answers

Pass ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE as the flag.

It's a bug: https://bugs.php.net/bug.php?id=71064 (since PHP 5.6.16)

There is an issue with the ZipArchive class' open() method. In previous versions of PHP when the only flag passed to the method was the ZipArchive::OVERWRITE, the method also created non-existing archives.

Since PHP 5.6 the OVERWRITE flag alone cannot create new archives which breaks compatibility.

like image 128
Gordon Avatar answered Sep 21 '22 11:09

Gordon