基於php下載檔案的詳解

來源:互聯網
上載者:User

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回應標頭

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.