流式传输大文件与PHP脚本



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

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的文件似乎仍然超时…我哪里做错了?

试试xmoovstream。它会帮你的。也是开源的

根据手册,使用readfile()

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

http://php.net/readfile

相关内容

  • 没有找到相关文章

最新更新