zip存档和下载无法正常工作

时间:2013-11-14 14:34:21

标签: php

我需要在index.php中创建一个zip文件。我的代码是:

$zip = new ZipArchive();

$DelFilePath="first.zip";

if(file_exists($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath)) {

        unlink ($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath); 

}
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
        die ("Could not open archive");
}
    $zip->addFile($_SERVER['DOCUMENT_ROOT']."/admin/index.php","file.php");

// close and save archive


$file=$_SERVER['DOCUMENT_ROOT']."/admin/Allorders/".$DelFilePath;

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

我得到一个0字节的zip文件。我的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

声明所有标题后,您需要回显实际数据。所以:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
echo $data;

其中$ data是您的zip存档的内容。

还可以在zip上尝试一些var_dump(),看看内存是否正常。

相关问题