PHP 关闭 zipArchive 打印垃圾文本(数据转储)


PHP Closing zipArchive prints junk text (data dump)

我一直在尝试学习如何正确使用 php 中的 zipArchive 函数来创建和下载包含选定文件的 zip 文件夹。

它工作,在时尚之后,创建 zip 文件并将其存储在服务器上,但我无法让下载自动开始,并且在 $zip->close(); 命令之后,它会打印一页又一页的垃圾字符,就好像它正在打印 zip 文件一样。这是其中的一部分:http://www.abpdigital.com/uploads/Junk%20Text.png

从这里得到了我的基本代码:http://roshanbh.com.np/2008/09/force-download-mutiple-files-zip-archive-php.html

下面是它在我的代码中的外观:

function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
    {
        //create the object
        $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();
        //THIS IS WHEN THE JUNK TEXT STARTS
        //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: Sat, 26 Jul 1997 05:00:00 GMT");
        readfile($archive_file_name);
        exit;
    }

有没有人知道可能导致垃圾文本的原因? 我是否错误地使用了标题? 如有必要,我可以提供进一步的代码,但我相当确定变量传递是可靠的。 我一直在Chrome中进行测试,但我已经验证了这种行为在IE和Firefox中仍然存在。

[更新] 我发现如果我在当前目录的子文件夹中(而不是直接在当前目录中)创建 zip 文件,它不会输出页面上的所有垃圾文本。

现在我的问题更多的是我希望从标题中获得的自动下载功能没有并且从未奏效。 就错误或事件而言,我应该寻找任何可能揭示问题所在的东西?

标题似乎有问题。显示的有线垃圾只是来自zip文件的原始数据。请检查$archive_file_name是否正确。尝试更改标头,如下所示:

// It should contain only the filename not the complete path
header("Content-Disposition: attachment; filename=".basename($archive_file_name));
// Adding file-size to header
header("Content-Length: " . filesize($archive_file_name));
// Check that is path to zip with filename
readfile($archive_file_name);