【问题标题】:PHP Downloading zip created with ziparchivePHP 下载使用 ziparchive 创建的 zip
【发布时间】:2018-12-06 19:41:34
【问题描述】:

我是 PHP 新手,正在尝试创建通过 ajax 调用并下载给用户的 ZIP 函数。 我通过 zip 得到了积极的回应,但流媒体给了我一个错误 filesize():stat failed for ../test.zip 并且读取文件失败打开流,php页面上没有这样的文件或目录。 下面是我的代码 - 我已经很努力了,似乎找不到适合我情况的答案

    <?php
    require("../../common.php");
    ini_set('display_startup_errors',1);
    ini_set('display_errors',1);
    error_reporting(-1);
$thisdir = " ";
$zip = new ZipArchive();
$filename = "../test.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}
$zip->addFromString('insert.pdf' . time(), "#1 This is a test string added as testfilephp.txt.\n");;
$zip->addFile($filename . "../../../folder/pdf_folder/");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
echo $filename;
//$size = filesize($zip->filename);
$zip->close();
header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$filename");
header("Content-length: " . filesize($filename));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$filename");
?>

感谢您的帮助或指导

******编辑 这是代码的错误

警告:filesize(): stat failed for ../test.zip in /var/---/----/---/----/第 21

警告 上的 control/ajax/zipAJAX.php
:readfile(../test.zip): 无法打开流: 在 /var/---/----/---/----/control/ajax/zipAJAX.php24 行中没有这样的文件或目录b>

【问题讨论】:

  • 能否将错误消息和堆栈跟踪复制到问题中?
  • 这是什么? $zip-&gt;addFile('../test.zip../../../folder/pdf_folder/')?两个参数应该用逗号分隔吗?此外,我不喜欢 $filename$zip-&gt;filename 不一致/二元性 - 也许只是避免它,我知道你可能正在调试。

标签: php ziparchive


【解决方案1】:

您不能使用 addFile 方法将文件夹的内容添加到 zip 文件中。您必须循环目录 (http://php.net/dir) 并使用 addFile 方法将每个文件添加到您的 zip 中。

在您将任何数据发回给用户之前,您可以检查 zip 文件是否存在。

$zip->close();
if(file_exists($file)) {
  header("Content-type: application/zip"); 
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-length: " . filesize($filename));
  header("Pragma: no-cache"); 
  header("Expires: 0"); 
  readfile("$filename");
}

还要检查用户在您要放置 zip 文件的目录中是否具有写入权限。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多