Search code examples
phpunzip

PHP - unzip / open returns integer


I'm trying to extract a csv file from a zip and I'm always getting an integer instead of a boolean in the following code.

$zip = "path_to_zip/zip.zip";
if (file_exists($zip))
   {    
      echo "Extracting";
      $z = new ZipArchive;
      $res = $z->open($zip);

      var_dump($res);
      if ($res === TRUE)
         {
            $z->extractTo("my_path/");
            $z->close();
         }
       else
         {
            echo "failed";
         }
   }

The zip file exists on the specified location as "Extracting" is displayed but then the $res variables return 19 as an integer and the script ends up with echoing "failed".

If I skip the line with $res === TRUE, I get the following message:

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

Do you see what's wrong with the object?


Solution

  • ZipArchive::open() returns bool|int (see https://www.php.net/manual/en/ziparchive.open.php#refsect1-ziparchive.open-returnvalues).

    The return value is true or a constant value.

    If you bypass the test $res === TRUE, $z is not ready to do operation ("Invalid or uninitialized Zip object"). You need to check it.

    For information 19 is the value of the constant ZipArchive::ER_NOZIP ("Not a zip archive."). So, $zip is not a valid zip file.

    To have a better view of the error state, you could do something like this :

    $z = new ZipArchive;
    $res = $z->open($zip);
    
    if ($res !== true)
    {
        switch($res) {
            case ZipArchive::ER_EXISTS: 
                echo 'File already exists.';
                break;
            case ZipArchive::ER_INCONS: 
                echo 'Zip archive inconsistent.';
                break;
            case ZipArchive::ER_INVAL: 
                echo 'Invalid argument.';
                break;
            case ZipArchive::ER_MEMORY: 
                echo 'Malloc failure.';
                break;
            case ZipArchive::ER_NOENT: 
                echo 'No such file.';
                break;
            case ZipArchive::ER_NOZIP: 
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                echo 'Not a zip archive but a ' . finfo_file($finfo, $zip);
                break;
            case ZipArchive::ER_OPEN: 
                echo 'Can\'t open file.';
                break;
            case ZipArchive::ER_READ: 
                echo 'Read error.';
                break;
            case ZipArchive::ER_SEEK: 
                echo 'Seek error.';
                break;
        }
    }
    else
    {
        // do stuff
    }