【问题标题】:Zip->close() returns false despite checks尽管检查,Zip->close() 仍返回 false
【发布时间】:2014-06-30 16:23:14
【问题描述】:

我正在尝试使用 ZipArchive 类创建一个 zip 文件。我在这里和那里阅读了很多内容并实施了很多检查(文件存在,目录可写..)。但是 zip->close() 仍然返回“false”,我不知道为什么。

if (!is_writable('../temp_downloads/')) { 
    die('directory not writable'); }

function create_zip($files = array(),$destination = '',$overwrite = false) {
    $destination = "../temp_downloads/".$destination.".zip";
    if(file_exists($destination) && !$overwrite) { return false; }
        $valid_files = array();

        if(is_array($files)) {
            foreach($files as $file) {
            if(file_exists('../data/'.$file) && is_readable('../data/'.$file)) {
                $valid_files[] = $file;
            }
        }
    }

    if(count($valid_files)) {
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            exit('cannot create zip');
        }

        foreach($valid_files as $file) {
            $zip->addFile($file,$file); // result returns 'true'
        }

        $res = $zip->close(); //$res contains 'false'

        if(file_exists($destination)){
            error_log("zip exists ".$destination);
            header("Content-type: application/zip"); 
            header("Content-Disposition: attachment; filename=$destination");
            header("Content-length: " . filesize($destination));
            header("Pragma: no-cache"); 
            header("Expires: 0"); 
            readfile("$destination");
        } else {
            error_log("ERROR: Zip doesnt exist at ".$destination);
        }

        return file_exists($destination);
    } else {    
        return false;
    }
}

我用这个函数调用

create_zip($files, 'PREFIX_'.$stamp, true);

其中 $files 是一个数组,而 $stamp 只是一个时间戳。 为了测试目标文件夹 chmod 设置为 777

你能帮帮我吗?

【问题讨论】:

    标签: php zip


    【解决方案1】:

    您(也许?)在压缩操作中为您的文件使用了不正确的路径:

    你在这里寻找../data/$file

    if(file_exists('../data/'.$file) && is_readable('../data/'.$file)) {
        $valid_files[] = $file;
    

    但在压缩时,您只需:

    $zip->addFile($file,$file);
    

    而不是

    $zip->addFile("../data/$file",$file);
    

    我不知道 addFile 是如何返回 true 的,除非您碰巧在脚本的当前工作目录中拥有所有这些文件的副本,或者您在 data 目录中工作并且 ../data.

    【讨论】:

    • 如果你盯着你的代码大约 2 小时就会发生这些事情。谢谢你的叫醒电话。我应该因为愚蠢而删除我的问题吗?
    • 这取决于您,但删除往往会对您的帐户产生负面影响。
    猜你喜欢
    • 2015-07-31
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2019-10-03
    • 1970-01-01
    • 2021-02-06
    • 2019-02-20
    相关资源
    最近更新 更多