Skip to content
Advertisement

Invalid or unitialized Zip object

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();
       } }

I am getting Warning: ZipArchive::addFile() [function.ZipArchive-addFile]: Invalid or unitialized Zip object. what could be problem? I tried many methods but in vain. I am able to create and initiate download when I select one file. However, I get above error when I select more than one file.

Advertisement

Answer

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();
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement