【问题标题】:Streaming Large Files with PHP Script使用 PHP 脚本流式传输大文件
【发布时间】:2011-08-27 21:08:26
【问题描述】:

使用在http://php.net/manual/en/function.fread.php 的 cmets 中找到的类似脚本,我设计了这个函数:

function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
    set_time_limit(0);
    $defaultchunksize = 1024*1024;
    $chunksize = $defaultchunksize;
    $buffer = '';
    $cnt = 0;
    $remotereadfile = false;

    if (preg_match('/[a-zA-Z]+:\/\//', $filename))
        $remotereadfile = true;

    $handle = @fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    header("Content-Type: application/octet-stream; ");
    header("Content-Transfer-Encoding: binary");
    header("Cache-Control: no-cache, must-revalidate");
    header("Content-Length: " . filesize($filename));
    header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");

    stream_set_timeout($handle, $timeout);

    if ($seek != 0 && !$remotereadfile)
        fseek($handle, $seek);

    while (!feof($handle)) {

        if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
            $chunksize = $seek-$cnt;
        else
            $chunksize = $defaultchunksize;

        $buffer = @fread($handle, $chunksize);

        if ($retbytes || ($remotereadfile && $seek != 0)) {
            $cnt += strlen($buffer);
        }

        if (!$remotereadfile || ($remotereadfile && $cnt > $seek))
            echo $buffer;

        ob_flush();
        flush();
    }

    $info = stream_get_meta_data($handle);

    $status = fclose($handle);

    if ($info['timed_out'])
        return false;

    if ($retbytes && $status) {
        return $cnt;
    }

    return $status;
}

但是,对于超过 100mb 左右的文件,它似乎仍然超时......我哪里可能出错了?

【问题讨论】:

  • 你试过readfile()吗?
  • 我的印象是 readfile() 将整个文件加载到内存中。
  • 不,它将文件流式传输到客户端
  • 一项快速测试表明 readfile() 确实将整个文件加载到内存中,但会像预期的那样将文件流式传输到客户端。
  • 查看源代码表明它没有:) bit.ly/pjcpYp -> bit.ly/nkbSge

标签: php stream


【解决方案1】:

试试 xmoovstream。它会为你做的。开源也是如此。

【讨论】:

    【解决方案2】:

    根据手册,使用readfile()

    注意: readfile() 不会出现任何内存问题,即使在发送大文件时也是如此。如果遇到内存不足错误,请确保使用 ob_get_level() 关闭输出缓冲。

    http://php.net/readfile

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      相关资源
      最近更新 更多