简体   繁体   中英

unable to create a valid zip file in php using zip archive?

I am using ziparchive to create a zip for some files and then need to download the file using the following code.

if(count($valid_files > 0)){
    $zip = new ZipArchive();
    $zip_name = "pixels.zip";
    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
        $error .= "* Sorry ZIP creation failed at this time";
    }

    foreach($valid_files as $file){
        $zip->addFile($file);
    }

    $zip->close();
    if(file_exists($zip_name)){
        // force to download the zip
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header('Content-type: application/zip');
        header('Content-Disposition: attachment; filename="'.$zip_name.'"');
        ob_clean();
        flush();
        readfile($zip_name);
     //remove zip file from temp path
        unlink($zip_name);
    }

} else {
    echo "No valid files to zip";
    exit;
}

Assuming that $valid_files contains an array with each element as the complete file path. The above code is expected to create a zip file containing the files but on the contrary once the download is initiated it keeps on downloading without any finishing size or maximum size. And in some cases even if the file is downloaded then when we try to unzip the file it gives an error as invalid file. Unable to figure out the issue any help is greatly appreciated.

造成这种情况的主要原因是,在同一文件夹中已经存在一个巨大的zip文件,该文件夹与我用来创建新zip的zip名称相同,因此由于某种原因未创建新zip且该旧的巨大zip开始下载,并且Marcelo在评论中建议的大小未提及,因此下载未成功,但是在以二进制形式声明的编码中提及大小并更改了zip名称或删除了先前的zip文件时,工作正常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM