【问题标题】:ZIP file not being created, but no error gets triggered未创建 ZIP 文件,但未触发任何错误
【发布时间】:2012-10-15 11:52:21
【问题描述】:

我正在使用 ZipArchive:

function zip_dir($source, $target){

    $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);

    $zip = new \ZipArchive();
    if($zip->open($target, \ZipArchive::CREATE) !== true)
      exit('cannot create zip');

    foreach($iterator as $file){
      $zip->addFile($file);
      print $file . '<br>';
    }


    $zip->close();
    return $target;
}


zip_dir(__DIR__ . '/test/', __DIR__ . '/testarchive.zip');

我可以看到文件列表,但最后我找不到应该创建的 zip 文件。而且我没有收到 ZipArchive 的错误/异常...

编辑:

我在$zip-&gt;close();之后添加了print $zip-&gt;getStatusString();

并打印:无法打开文件:权限被拒绝”。 这意味着什么?我确定每个目录都是可写的,因为我可以在其中创建带有 PHP 的新文件...

编辑 2:

if(is_writable(dirname($target)))
  print 'target dir is writable...';

它打印出来,所以目录是可写的。感觉就像我在暮光之城...

【问题讨论】:

  • 运行 PHP 的用户是否有权在相关目录中创建文件?
  • 测试目录是否可写
  • 是的,我在本地主机上运行“wamp”。它有权做任何事情..
  • 使用 try catch 看看代码是否抛出异常
  • addFile 返回的是真还是假?

标签: php file zip ziparchive


【解决方案1】:

来自 php.net 的两条评论

如果您将多个文件添加到一个 zip 并且您的 $zip-&gt;close() 调用返回 FALSE,请确保您添加的所有文件确实存在。显然$zip-&gt;addFile() 会返回 TRUE,即使该文件实际上并不存在。在调用$zip-&gt;addFile() 之前,最好使用file_exists()is_readable() 检查每个文件。

别忘了检查 zip 是否为空,伙计们 - 否则根本不会创建 zip,服务器也不会发出警告!

【讨论】:

  • 如何检查zip文件是否为空?
  • $zip 的 numFiles 属性是 9。我猜这意味着它不是空的
  • 和“status”是5,“statusSys”是2
  • 好吧,我最终做到了。似乎空目录会触发此错误:|
  • 此外,在迭代文件夹时,请确保排除每个文件夹中的前两项(...)。
【解决方案2】:

听起来您有权限问题,要么是写入 zip 文件,要么是读取它正在压缩的文件。

我会使用file_existsis_readableis_writable 的组合来找出导致问题的原因。

function zip_dir($source, $target){

    $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);

    $zip = new \ZipArchive();
    if($zip->open($target, \ZipArchive::CREATE) !== true)
      exit('cannot create zip');

    foreach($iterator as $file){
      if (!file_exists($file)) { die($file.' does not exist'); }
      if (!is_readable($file)) { die($file.' not readable'); }
      $zip->addFile($file);
      print $file . '<br>';
    }


    $zip->close();
    return $target;
}

if (!is_writable(__DIR__)) { die('directory not writable'); }
zip_dir(__DIR__ . '/test/', __DIR__ . '/testarchive.zip');

【讨论】:

    【解决方案3】:

    确保:

    • 添加的所有文件都实际存在(在调用$zip-&gt;addFile() 之前,使用file_exists()is_readable() 检查每个文件)。
    • 迭代文件夹时,排除...
    • 至少有一个要压缩的文件 ($zip['numFiles'] &gt; 0)。
    • 调用$zip-&gt;close() 返回TRUE

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 2014-10-14
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多