【问题标题】:Debugging zip archive and download调试 zip 存档和下载
【发布时间】:2018-08-06 19:11:28
【问题描述】:

我需要一些帮助来调试这段代码。我正在尝试压缩一些文件,这些文件作为 Ziparchive 的路径提供。我认为 zip 文件可能是空的。当我在暂存站点上进行测试时,我收到“解压失败”错误。当我在本地测试时,我在 php 日志中收到以下错误

PHP 警告:readfile(images.zip):无法打开流:第 29 行的 /Applications/MAMP/htdocs/8018_Whites/wordpress/downloadzip.php 中没有此类文件或目录。

代码如下:

<?php

//get image urls string
//$cat_string = "url1,url2,url3..."
if (isset($_GET['category-images'])) {
    $cat_string=$_GET['category-images'];
}
//change string to array
$cat_array=explode(",", $cat_string);
$files=$cat_array;

$zipname = 'images.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  if(!strstr($file,'.php')) $zip->addFile($file);
}
$zip->close();

if ($zipname) {
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
exit();
}
?>

我需要在这段代码中添加ob_start/ob_flush吗,我应该把ob_flush放在readfile之后吗?

【问题讨论】:

    标签: php wordpress ziparchive


    【解决方案1】:

    所有文件和 Zip 文件夹给出绝对路径。因此 zip 已正确创建。

    <?php
    $zip_root ='/var/www/gplhome/'
    $file_root ='/var/www/gplhome/project/'
    
        //get image urls string
        //$cat_string = "url1,url2,url3..."
        if (isset($_GET['category-images'])) {
            $cat_string=$_GET['category-images'];
        }
        //change string to array
        $cat_array=explode(",", $cat_string);
        $files=$cat_array;
    
        $zipname = $zip_root.'images.zip';
        $zip = new ZipArchive;
    
    
        if ($zip->open($zipname, ZIPARCHIVE::CREATE) != TRUE) {
            die("Could not open archive");
        }
    
        foreach ($files as $file) {
          if(!strstr($file_root.$file,'.php')) $zip->addFile($file_root.$file);
        }
        $zip->close();
    
    if ($zipname) {
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename='.$zipname);
        header('Content-Length: ' . filesize($zipname));
        readfile($zipname);
        exit();
    }
    ?>
    

    【讨论】:

      【解决方案2】:
      • 检查$zip->close()的返回值,出错返回false。
      • 检查$zip->addFile()的返回值,出错返回false。
      • 确保您只对标题使用文件名,对 readfile 使用全名。
      • 检查文件是否已创建。替换

      if ($zipname) {

      if (is_readable($zipname)) {

      • 不要把?&gt;和php文件的结尾放在一起

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 1970-01-01
        • 2023-03-07
        • 2020-02-17
        • 2013-08-20
        • 2012-04-04
        • 2011-11-15
        相关资源
        最近更新 更多