【问题标题】:PHP force download results in corrupted filePHP强制下载导致文件损坏
【发布时间】:2013-07-12 17:12:35
【问题描述】:

我有一个强制下载的 PHP 脚本。这是我的代码

//$file and $mime have been set earlier
$basename = basename($file);
$length   = sprintf("%u", filesize($file));
header('Content-Description: File Transfer');
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="' . $basename . '"');
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: ' . $length);
set_time_limit(0);
readfile($file);

现在这个脚本可以在我的本地服务器上完美运行,但是当我将它上传到我的网站并试用它时,文件下载(为了测试它我使用了一张图片),但是当我打开它时,我得到了@987654322 @

我在 Sublime Text 中打开了文件,它是这样写的
警告:set_time_limit() [function.set-time-limit]:无法在 /mounted-storage/home61c/sub001/sc38639-USWQ/www 中的安全模式下设置时间限制/test/scripts/download.php32 行
‰PNG

bla bla bla(我无法复制和粘贴下面的内容)

发生了什么事?

【问题讨论】:

  • 这听起来不像是文件损坏了,听起来你遇到了 PHP 错误。当然,您无法在 Windows 照片查看器中打开文本错误消息。

标签: php download php-safe-mode


【解决方案1】:

set_time_limit 在安全模式下无效,并且该警告会滑入您的输出中,破坏它。 见http://www.php.net/manual/en/features.safe-mode.functions.phphttp://php.net/manual/en/features.safe-mode.php

尝试关闭安全模式或不使用 set_time_limit 并尝试延长 php.ini 中的默认运行时间,请参阅http://www.php.net/manual/en/function.set-time-limit.php

【讨论】:

    【解决方案2】:

    你有两个选择:

    评论这一行:

    set_time_limit(0);
    

    禁用安全模式。

    【讨论】:

      【解决方案3】:

      你可能在输出缓冲区中得到了一些不需要的东西。

      包括

      flush();
      ob_clean();
      

      在开始下载之前,请确保一切都干净。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多