PHP處理大文件下載

思路:PHP一邊讀取文件,一邊將讀取到的內容輸出到瀏覽器中

<?php
/**
 * Created by PhpStorm.
 * User: Kung
 * Date: 15-10-21
 * Time: 下午8:00
 */
set_time_limit(0);  //大文件在讀取內容未結束時會被超時處理,導致下載文件不全。

$fpath = 'the_file_path';
$file_pathinfo = pathinfo($fpath);
$file_name = $file_pathinfo['basename'];
$file_extension = $file_pathinfo['extension'];
$handle = fopen($fpath,"rb");
if (FALSE === $handle)
    exit("Failed to open the file");
$filesize = filesize($fpath);

header("Content-type:video/mpeg4");//更具不同的文件類型設置header輸出類型
header("Accept-Ranges:bytes");
header("Accept-Length:".$filesize);
header("Content-Disposition: attachment; filename=".$file_name);

$contents = '';
while (!feof($handle)) {
    $contents = fread($handle, 8192);
    echo $contents;
    @ob_flush();  //把數據從PHP的緩衝中釋放出來
    flush();      //把被釋放出來的數據發送到瀏覽器
}
fclose($handle);
exit;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章