Invalid or unitialized Zip object

According to the documentation you cannot OR the open mode flags, you can only open in one mode. Check the file exists first and set the mode on open appropriately and see if that helps.


the library itself gives you a code to see why it fails:

$ZIP_ERROR = [
  ZipArchive::ER_EXISTS => 'File already exists.',
  ZipArchive::ER_INCONS => 'Zip archive inconsistent.',
  ZipArchive::ER_INVAL => 'Invalid argument.',
  ZipArchive::ER_MEMORY => 'Malloc failure.',
  ZipArchive::ER_NOENT => 'No such file.',
  ZipArchive::ER_NOZIP => 'Not a zip archive.',
  ZipArchive::ER_OPEN => "Can't open file.",
  ZipArchive::ER_READ => 'Read error.',
  ZipArchive::ER_SEEK => 'Seek error.',
];

$result_code = $zip->open($zip_fullpath);
if( $result_code !== true ){
   $msg = isset($ZIP_ERROR[$result_code])? $ZIP_ERROR[$result_code] : 'Unknown error.';
   return ['error'=>$msg];
}

The power of indenting correctly!

You are closing your zip file inside your loop.

If I re-format your code it becomes obvious.

Corrected code follows:

if(isset($_POST['items'])) {
  // open zip
  $zip_path = 'downloadSelected/download.zip';
  $zip = new ZipArchive();

  if ($zip->open($zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
    die ("An error occurred creating your ZIP file.");
  }

  foreach ($_POST['items'] as $path) {

    // generate filename to add to zip
    $filepath = 'downloads/' . $path . '.zip';

    if (file_exists($filepath)) {
      $zip->addFile($filepath, $path . '.zip') or die ("ERROR: Could not add the file $filename");
    } else {
      die("File $filepath doesnt exit");
    }
  }

  $zip->close();
}

Tags:

Php

Zip