通过ZipArchive php获取损坏或空拉链

问题描述 投票:6回答:5

我通过以下代码下载zip文件,没有任何错误,但下载的zip文件为空或已损坏,大小总是大约200字节。即我无法打开该zip文件。 ZipArchive :: getStatusString()也显示“No error”

代码是:

public function getzip(){
    global $config;
    $files=array();
    if(isset($_COOKIE['hashes'])){
        $hashes=explode(',',$_COOKIE['hashes']);
        for ($i=0; $i <count($hashes); $i++) {
            array_push($files,$config["domain"]."/download/".$hashes[$i]); 
        }
    }
    if(count($files)){
        $zipname='basket.zip';
        $zip = new ZipArchive;
        $zip->open($zipname,ZipArchive::CREATE);
        foreach ($files as $key=>$value ) {
            $zip->addFile($value);
        }
        $status=$zip->getStatusString();
        $zip->close();

    if(!$zipname)
    {
        echo "Nothing in Basket";
    }
    else
    {   header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition:attachment; filename='.basename($zipname));
        header('Content-Length:'.filesize($zipname));
        readfile($zipname);
    }
}
php zip ziparchive
5个回答
3
投票

这是我最好的猜测。这里出了什么问题,在你的数组$files中,你存储的值可能不是文件的实际路径。

请记住:您无法将URL传递到$zip->addfile(),您需要实际的文件。


5
投票

尝试在$zip->close();之前获取完整的文件路径和名称

$filename = $zip->filename;

并在读取文件和获取文件大小时使用它而不是$zipname


1
投票

即使这个问题很难解决,我也会发布我发现如何创建损坏的拉链:

制作zip存档时,通常会使用echo / print_r命令进行调试。如果你不清除这些,输出zip文件将被破坏。

基于问题的示例:

public function getzip(){
    global $config;
    $files=array();
    if(isset($_COOKIE['hashes'])){
        $hashes=explode(',',$_COOKIE['hashes']);
        for ($i=0; $i <count($hashes); $i++) {
            array_push($files,$config["domain"]."/download/".$hashes[$i]); 
        }
    }
    if(count($files)){
        $zipname='basket.zip';
        $zip = new ZipArchive;
        $zip->open($zipname,ZipArchive::CREATE);
        foreach ($files as $key=>$value ) {
            $zip->addFile($value);
        }
        $status=$zip->getStatusString();
        $zip->close();

    if(!$zipname)
    {
        echo "Nothing in Basket";
    }
    else
    {   
        // to fix your corrupt zip file, remove this line.
        echo 'THIS IS AN EXAMPLE DEBUG: ' . $zipname;
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition:attachment; filename='.basename($zipname));
        header('Content-Length:'.filesize($zipname));
        readfile($zipname);
    }
}

1
投票

即使原始问题已经解决,因为我只花了几个小时来处理类似的问题,因此添加到此线程。

事实证明,在执行$ zip-> close()时,所有文件都需要存在,无论您何时使用$ zip-> addFile()添加它们。

因此,如果您创建临时文件,将它们添加到zip中,然后在使用close()之前将其删除,则最终可能会出现空/损坏的存档。


0
投票

我通过将代码移动到我想要添加到Zip存档的文件所在的同一文件夹来解决了同样的问题。

© www.soinside.com 2019 - 2024. All rights reserved.