【问题标题】:download Zip file which is formed by multiple files in PHP下载由 PHP 中的多个文件组成的 Zip 文件
【发布时间】:2012-07-14 17:39:15
【问题描述】:

我有一些 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 的名称更改为上面给出的名称以外的名称,我会收到Archive 已损坏的错误消息。我不知道为什么会这样 2.如果我有一个 zip 文件,比如说 2 个 pdf,然后我再次下载一个只有 1 个 pdf 的 zip,这与之前的不一样。但是当我下载 1 个 pdf 的 zip 时,我得到了 3 个 pdf ......我不知道为什么......请帮帮我。

【问题讨论】:

  • 你试过哪个名字?哪个好?
  • 我已经尝试过 zipper1.zip,但它不起作用。它只使用 zipper.zip 名称。

标签: php html zip


【解决方案1】:

我测试了您的 zipFilesAndDownload 函数,它运行良好。所以首先你应该检查你的脚本,是否在&lt;?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 detecting filesystem encodingHow do I use filesystem functions in PHP, using UTF-8 strings?

【讨论】:

  • 它工作正常,但我仍然面临 2 个问题,1。如果我将archive_file_name 的名称更改为上面给出的名称以外的名称,我会收到Archive 已损坏的错误消息。我不知道为什么会这样 2.如果我有一个 zip 文件,比如说 2 个 pdf,然后我再次下载一个只有 1 个 pdf 的 zip,这与之前的不一样。但是当我下载 1 个 pdf 的 zip 时,我得到了 3 个 pdf ......我不知道为什么......请帮助我。
  • 嗨,我也不知道为什么。但是您可以在一些 hexaviewer 中检查压缩文件,看看它是否以 PK 字母开头正确。除此之外我不知道。
猜你喜欢
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多