通过标头下载时 ZIP 文件已损坏 [英] ZIP file corrupted when downloaded by header

查看:55
本文介绍了通过标头下载时 ZIP 文件已损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a zip file through php around 2-3mbs and at the end i want to send that zip file to the user for download.

不幸的是,由于某种原因,使用以下内容不起作用.嗯,它有效,但不像它应该的那样.该文件按原样到达浏览器.我下载它,打开它,但是当我尝试提取或查看其中的文件时,它崩溃了,说它已损坏.但是,如果我去打开目录 zip 文件中存在的文件,则可以正常打开,我可以提取查看那里的所有内容.任何想法为什么会发生这种情况?

Unfortunately using the below does not work for some reason. Well it works but not as it was supposed to. The file gets to the browser as it should. I download it, open it but when i try to exract or view the files inside it breaks down saying it's corrupted. If however i go and open the file that exists in the directory zip file opens fine and i can exract-view everything there. Any ideas why is this happening?

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

推荐答案

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

Try add exit(); on the end of script. It is possible that script send inadvertently whitespace after commands readfile(), for example whitespace after the ?>

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

It is also suitable to use ob_start() ob_clean() functions.

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

这篇关于通过标头下载时 ZIP 文件已损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆