PHP标头()在Chrome和Firefox中失败

时间:2015-08-16 20:26:37

标签: php google-chrome header

以下代码适用于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目录之外的文件。

我似乎无法找到解决办法,任何想法?

2 个答案:

答案 0 :(得分:0)

过去我在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();
    ?>

答案 1 :(得分:0)

只需删除ob_clean()行对我有用。