2011-08-27 44 views
0

大文件使用的http://php.net/manual/en/function.fread.php評論中發現一個類似的腳本,我已經設計了這個功能:流與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左右的文件時間了..我哪裏可能會出錯?

+1

你試過用'ReadFile的()'? – arnaud576875

+0

我的印象是readfile()將整個文件加載到內存中。 – Bryan

+0

不,它將文件流式傳輸到客戶端 – arnaud576875

回答

0

嘗試xmoovstream。它會爲你做。開源。

0

根據手冊,使用readfile()

注: ReadFile的()不會出現內存問題,發送大文件,即使上了自己。如果遇到內存不足錯誤,請確保使用ob_get_level()關閉輸出緩衝。

http://php.net/readfile