作者previa (Southern Cross)
看板PHP
標題Re: [請益] readfile 效率問題
時間Mon Jul 17 05:14:10 2006
※ 引述《KoShiyen (http://0rz.net/e70jv)》之銘言:
: 我寫了一個程式過濾下載的使用者
: 通過的才會用 readfile 放檔案給他, 否則會改放拒絕的圖檔
: 可是本來直接下載時很快很容易下載的檔
: 透過 readfile 就變成慢得不得了
: 開一個檔常常要等好幾分鐘才開始下載
: 用不同的 webhost 也是得到同樣的結果
: 請問這是設定的問題還是程式的問題?
: 用 readfile 釋出檔案前需要什麼特別的處理嗎?
: 謝謝.
這是我在別的地方看到的 我也有這個困擾 XD
http://theserverpages.com/php/manual/en/function.readfile.php
regarding php5:
i found out that there is already a disscussion @php-dev about readfile()
and fpassthru() where only exactly 2 MB will be delivered.
so you may use this on php5 to get lager files
<?php
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
?>
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.140.55.7
※ 編輯: previa 來自: 220.140.55.7 (07/17 05:14)
※ 編輯: previa 來自: 220.140.55.7 (07/17 05:16)
推 KoShiyen:我也有看到這篇, 用這個方法確實快很多 07/17 11:48
→ KoShiyen:可惜還是比不上直接 embed 的速度 不過還是感謝您 orz 07/17 11:49
推 kenshieh:大型檔案建議都用此方法 因為 readfile 會把整個檔案先 07/17 16:59
→ kenshieh:讀到記憶體 之後再寫入 所以一定很慢 07/17 17:00
→ kenshieh:這方法 io 雖然多次 但一次讀的少自然而然就快多了 07/17 17:00