[英]download Zip file which is formed by multiple files in PHP
我有一些pdf文件...我只想将它们作为一个集合而不是一个一个地下载。 为此,我正在尝试压缩所有pdf文件并下载。 但是我不知道为什么在我的代码中更改ZipArchive文件名时会说损坏和损坏。 我的代码如下:
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE )!==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);
}
$zip->close();
//then send the headers to foce 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;
}
if($button=="Save as pdf")
{
$file_names = array();
foreach($a as $key=>$as)
{
$file_names[] = $key.'.pdf';
}
}
$archive_file_name='zipped.zip';
$file_path='/resume/';
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
?>
有人可以帮我吗? 提前致谢。
它的工作正常,但我仍然面临2个问题,1。 如果我将archive_file_name的名称更改为上面给出的名称以外的其他名称,则会收到存档损坏的错误消息。 我不知道它为什么会发生2.如果我有一个说2个pdf的zip文件,然后我再次下载了仅1个pdf的zip,这与以前的zip不同。 但是,当我下载1 pdf的zip时,我得到3 pdf……我不知道为什么........请帮助我。
我测试了您的zipFilesAndDownload
函数,它运行良好。 因此,首先应检查脚本,在<?php
起始标记之前是否发送了字符或空格。
如果您的脚本在CMS中运行,则还应该清除所有输出缓冲区: while (@ob_end_clean());
(如果已经发送了gzip标头,则还要再次打开gz压缩ob_start('ob_gzhandler');
)
另外,您还可以检查是否正确设置了$ file_path并且所有文件都存在,例如:
$file_path='resume/';
if (!file_exists($file_path) || !is_dir($file_path)) {
die("Invalid directory $file_path in ".getcwd());
}
// you can test the existence of your problematic files:
foreach ($file_names as $file) {
if (!file_exists($file_path.$file)) {
echo "$file not found.";
} else {
echo "$file is ok.";
}
}
exit;
// end of test
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
在Windows中,UTF-16 / UTF-8 /国际字符编码也存在问题,请参见此处: PHP检测文件系统编码 , 如何使用UTF-8字符串在PHP中使用文件系统功能? 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.