php - 创建一个 zip 文件并下载

标签 php download zip

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

我为此使用的以下代码:

 <?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>\n");
    }
    //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;
}




?>

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

最佳答案

添加Content-length以字节为单位描述 zip 文件大小的 header 。

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");

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

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

关于php - 创建一个 zip 文件并下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12225964/

相关文章:

php - 记住从数据库填充的用户复选框

c# - 如何生成包含 JSON 结构的要下载的文件?

java - 使用系统首选应用程序显示 zip 内的文件而不使用 java 解压缩?

php - 如何使用 DOMDocument 更改 xml 源

php - 使用 fopen()、fgets() 和 PHP 的流式 JSON 解析器

php - 在 PHPUnit_Extensions_Selenium2TestCase 中处理 HTTP 状态代码

PowerShell FTP 下载文件和子文件夹

Java 不喜欢下载文件。

xml - 从解压缩的 xml 文件夹重新创建 excel .xlsx 文件

java - 递归地Uzip文件夹-android