按标题下载时ZIP文件已损坏

时间:2014-07-02 11:26:48

标签: php zip

我正在通过php创建一个大约2-3mbs的zip文件,最后我想将该zip文件发送给用户下载。

不幸的是,由于某些原因,使用以下内容不起作用。好吧它有效,但不是应该的。 该文件应该到达浏览器。我下载它,打开它,但当我尝试exract或查看其中的文件时,分解说它已损坏。但是,如果我去打开目录zip文件中存在的文件打开正常,我可以exract - 查看那里的一切。 任何想法为什么会发生这种情况?

if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($zip_name)) {
        header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
        echo 'File not found';
    } else if (!is_readable($zip_name)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo 'File not readable';
    } else {
        header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: ".filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"".$zip_name."\"");
        readfile($zip_name);
    }
}

1 个答案:

答案 0 :(得分:2)

尝试在脚本末尾添加 exit(); 。命令 readfile()后,脚本可能会无意中发送空格,例如?> 之后的空白

也适合使用 ob_start() ob_clean()函数。

    ob_start();

    // .... some code

    header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: Binary");
    header("Content-Length: ".filesize($zip_name));
    header("Content-Disposition: attachment; filename=\"".$zip_name."\"");

    // disable cache
    header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header("Cache-control: private");
    header('Pragma: private');

    ob_end_clean();
    readfile($zip_name);

    exit();      
相关问题