php下載檔案,比如txt檔案。
出現的效果就是,彈出瀏覽器內建的下載框,出現另存新檔操作。有時候會出現記憶體溢出和逾時的現象。
逾時的話,設定
set_time_limit(0);
出現記憶體溢出的話,有可能是因為從資料庫中取出的資料量太大導致的。
如果是從檔案中讀取的話,出現記憶體溢出的話,就是代碼讀取方式不正確,調用files或者filegetcontens才會
如果是fopen的話,就給一個緩衝區,固定大小,讀入然後寫入,不會出現記憶體溢出的情況。
如代碼:
複製代碼 代碼如下:if (file_exists($file_path)) { //如果檔案存在
$handle = fopen($file_path, "r");
while (!feof($handle)) {
$content = fgets($handle, 4096); //讀取一行
echo $content; //輸出到緩衝區,即php://stdout。達到緩衝區設定值後由tcp傳給瀏覽器進行輸出 一般到512位元組就會通過網路輸出給瀏覽器
}
fclose($handle);
}
但是在輸出之前,要調用一次,@ob_end_flush();不能迴圈調用,只調用一次就好。
@ob_end_flush();//沖刷出(送出)輸出緩衝區內容並關閉緩衝
檔案下載:
content-type://下載的格式,瀏覽器不能解析的格式就會彈出下載框
複製代碼 代碼如下:header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
Header("Content-type: application/octet-stream"); //響應內容類型
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($filename). ' bytes');
Header('Content-Disposition: attachment; filename='.$filename); //HTTP回應標頭