创建一个 zip 文件并下载它

2022-01-02 00:00:00 download zip php

我试图通过在本地服务器上创建 zip 文件来下载 2 个文件.该文件以 zip 格式下载,但是当我尝试解压缩它时.它给出了错误:未找到中央目录结尾签名.要么这个文件不是一个 zip 文件,或者它构成一个多部分存档的磁盘.在里面后一种情况,将在以下位置找到中央目录和 zip 文件注释此存档的最后一个磁盘.

I am trying to download a 2 files by creating the zip file on local-server.the file is downloaded in zip format but when i try to extract it.it gives error: End-of-central-directory signature not found. Either this file is not a zip file, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zip file comment will be found on the last disk(s) of this archive.

我为此使用的以下代码:

the following code i am using for this:

 <?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');

//Archive name
$archive_file_name=$name.'iMUST_Products.zip';

//Download Files path
$file_path=$_SERVER['DOCUMENT_ROOT'].'/Harshal/files/';


zipFilesAndDownload($file_names,$archive_file_name,$file_path);

function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
        //echo $file_path;die;
    $zip = new ZipArchive();
    //create the file and throw the error if unsuccessful
    if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>
");
    }
    //add each files of $file_name array to archive
    foreach($file_names as $files)
    {
        $zip->addFile($file_path.$files,$files);
        //echo $file_path.$files,$files."

    }
    $zip->close();
    //then send the headers to force download the zip file
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$archive_file_name"); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$archive_file_name");
    exit;
}




?>

我检查了传递给函数的所有变量的值,一切都很好.所以请看这个.提前致谢.

i checked the values of all variables which are passing into the function,all are fine.so please look this.Thanks in advance.

推荐答案

添加 Content-length 标头,以字节为单位描述 zip 文件的大小.

Add Content-length header describing size of zip file in bytes.

header("Content-type: application/zip"); 
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Content-length: " . filesize($archive_file_name));
header("Pragma: no-cache"); 
header("Expires: 0"); 
readfile("$archive_file_name");

还要确保 之前和 ?> 之后绝对没有空格.我在这里看到一个空格:

Also make sure that there is absolutely no white space before <? and after ?>. I see a space here:

 <?php
$file_names = array('iMUST Operating Manual V1.3a.pdf','iMUST Product Information Sheet.pdf');

相关文章