尽管有检查,Zip->close() 仍返回 false [英] Zip->close() returns false despite checks

查看:35
本文介绍了尽管有检查,Zip->close() 仍返回 false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a zip file with the ZipArchive class. I was reading a lot here and there and implemented a lot of checks (file existence, directory writable..). But zip->close() still returns 'false' and I can't figure out why.

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

where $files is an array and $stamp just a timestamp. For testing the destination folders chmod is set to 777

你能帮我吗?

推荐答案

您(可能?)在 zip 操作中使用了错误的文件路径:

You're (maybe?) using incorrect paths for your files in the zip operations:

在这里寻找../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.

I don't see how addFile could return true, unless you coincidentally happen to have duplicates of all those files in the script's current working directory, or you ARE working in a data directory and ../data is the same as .

这篇关于尽管有检查,Zip->close() 仍返回 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆