【问题标题】:How to write PHP script for proper file download?如何编写 PHP 脚本以正确下载文件?
【发布时间】:2012-06-30 14:43:30
【问题描述】:

我无法解决文件下载问题。在 Chrome 中,下载工作正常。在 Firefox 中,它会在文件末尾生成一些 HTML 标题,例如:

<!DOCTYPE .....>
...
...

对于其他一些浏览器,下载的文件也会丢失一些行。如何编写脚本以使其真正适用于许多浏览器?这是我当前的代码:

private  function downloadRawFileHelper($file) {
    if (ini_get('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }
    if (!file_exists($file)) {
        die('File Not Found');
    }

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: text/php");
    header("Content-Disposition: attachment; filename=\"". basename($file). "\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    $this->view = 'fileedit';
}

【问题讨论】:

  • 您应该开始意识到这与任何特定的网络浏览器都无关。

标签: php http cross-browser cache-control


【解决方案1】:

尝试在 readfile 之后加上 exit ,我认为这会解决您的问题

【讨论】:

    【解决方案2】:

    我找不到代码有任何问题。您可以尝试在函数末尾添加exit()die()。将其更改为:

    private  function downloadRawFileHelper($file) {
        if (ini_get('zlib.output_compression')) {
            ini_set('zlib.output_compression', 'Off');
        }
        if (!file_exists($file)) {
            die('File Not Found');
        }
    
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false);
        header("Content-Type: text/php");
        header("Content-Disposition: attachment; filename=\"". basename($file). "\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        $this->view = 'fileedit';
        exit();
    }
    

    您正在将文件输出到浏览器。所以你需要在那之后停止脚本执行。

    希望这会有所帮助:)

    【讨论】:

      【解决方案3】:

      flush() 之前添加ob_end_clean();exit()readfile() 之后。另外,您可以考虑使用 X-SendFile 而不是纯 PHP 将文件发送到客户端,因为在大文件的情况下会占用宝贵的资源。

      【讨论】:

        【解决方案4】:

        这是你的问题:

        header("Content-Disposition: attachment; filename=\"". basename($file). "\"");
        

        尝试为您的档案命名,例如:

        header("Content-Disposition: attachment; filename=\"". basename($file). "filename.extension\"");
        

        【讨论】:

          【解决方案5】:

          调试 HTTP 问题的最佳方法是实际检查发送的 HTTP 消息。今天的浏览器使这变得非常容易。

          如果站点是公开的,您可以尝试 redbot.org 来检查响应。

          最后,您要发送大量未定义和/或无用的响应标头字段,例如“Content-Transfer-Encoding”或 Cache-Control 中的“检查”指令。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-01-23
            • 2010-12-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-15
            • 1970-01-01
            相关资源
            最近更新 更多