调试zip存档和下载

时间:2015-03-25 13:01:40

标签: php wordpress ziparchive

我想帮助调试这段代码。我试图压缩一些文件,我将其作为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,是否应该在readfile之后放置ob_flush?

2 个答案:

答案 0 :(得分:0)

所有文件和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();
}
?>

答案 1 :(得分:0)

  • 检查$ zip-> close()的返回值,错误时返回false。
  • 检查$ zip-> addFile()的返回值,错误时返回false。
  • 确保仅将文件名用作标题,将全名用作readfile。
  • 检查是否已创建文件。替换

if ($zipname) {

if (is_readable($zipname)) {

  • 不要将?>和php文件的末尾
相关问题