下载由PHP中的多个文件组成的Zip文件


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

有人能帮我吗?提前谢谢。

它运行良好,但我仍然面临两个问题,1。如果我将Archive_file_name的名称更改为上面给出的名称以外的名称,我会收到一个错误,即Archive已损坏。我不知道为什么会发生这种情况2.如果我有一个zip文件,比如说2个pdf,然后我再次下载一个只有1个pdf的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检测文件系统编码,如何在PHP中使用文件系统函数,使用UTF-8字符串?。