我正在尝试通过在本地服务器上创建 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/