douhuang1973 2014-07-02 11:26
浏览 63

ZIP文件下载时ZIP文件损坏[重复]

This question already has an answer here:

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.

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);
    }
}
</div>
  • 写回答

1条回答 默认 最新

  • doushenyu8228 2014-07-02 12:11
    关注

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

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?