【问题标题】:PHP header() failing in Chrome and FirefoxPHP header() 在 Chrome 和 Firefox 中失败
【发布时间】:2015-08-16 20:26:36
【问题描述】:

以下代码适用于 Safari,但不适用于 Firefox 或 Chrome

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    ob_end_flush();
    exit;

XXXX 的网页可能暂时关闭,或者它可能已永久移至新网址。 错误代码:ERR_INVALID_RESPONSE

$file 变量链接到 public_html 目录之外的文件。

我似乎找不到解决办法,有什么想法吗?

【问题讨论】:

    标签: php google-chrome header


    【解决方案1】:

    过去我在 chrome 和 firefox 上遇到过 filesize() 问题。这是我的解决办法。

       <?php
        Function real_filesize($file) {
    
          $fmod = filesize($file);
          if ($fmod < 0) $fmod += 2.0 * (PHP_INT_MAX + 1);
          $i = 0;
          $myfile = fopen($file, "r");
          while (strlen(fread($myfile, 1)) === 1) {
            fseek($myfile, PHP_INT_MAX, SEEK_CUR);
            $i++;
          }
          fclose($myfile);
          if ($i % 2 == 1) $i--;
    
          return ((float)($i) * (PHP_INT_MAX + 1)) + $fmod;
    
        }
    
    
        $filename = "somefile.ext";
        $filepath = "some/dir/path/to/file/".$filename;
        $filesize = real_filesize($filepath);
    
        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download'); 
        header('Content-Type: application/octet-stream');
        header("Content-Type: application/download");
        header("Content-Disposition: attachment; filename=".basename($filename).";");
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . $filesize);
        ob_clean();
        flush();
        readfile($filepath);
        exit();
        ?>
    

    【讨论】:

      【解决方案2】:

      刚刚删除了 ob_clean() 为我工作的行。

      【讨论】:

        猜你喜欢
        • 2012-04-01
        • 2016-10-14
        • 2015-07-02
        • 1970-01-01
        • 2012-02-05
        • 2015-09-29
        • 1970-01-01
        • 2017-08-15
        • 2021-07-20
        相关资源
        最近更新 更多