繁体   English   中英

无效或未初始化的 Zip 对象

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

我收到警告: ZipArchive::addFile() [function.ZipArchive-addFile]: Invalid or unitialized Zip object 可能有什么问题? 我尝试了很多方法,但徒劳无功。 当我选择一个文件时,我能够创建和启动下载。 但是,当我选择多个文件时,出现上述错误。

正确缩进的力量!

您正在关闭循环中的 zip 文件。

如果我重新格式化您的代码,它变得显而易见。

更正后的代码如下:

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

库本身为您提供了一个代码来查看它失败的原因:

$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];
}

根据文档你不能或打开模式标志,你只能在一种模式下打开。 首先检查文件是否存在并适当地设置打开模式,看看是否有帮助。

您也可能使用php://output作为文件名(不是针对问题作者,而是针对搜索此错误的任何人),ZipArchive 不支持这种情况。

如果您需要输出 zip 文件,请将其保存到临时文件,然后使用readfile功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM