大文件下載如何不導(dǎo)致內(nèi)存溢出
public function testDownload(){
? ? ? ? set_time_limit(0);
? ? ? ? //$file_name = 'live.mp4';
? ? ? ? // 打開文件
? ? ? ? $newf = fopen(storage_path('logs/').'video','wb');
? ? ? ? $logf = fopen(storage_path('logs/').'memory','wb');
? ? ? ? $url = 'http://minsheng.zmeng123.com/admin/Index/index.html';
? ? ? ? $fp = fopen($url, 'rb');
? ? ? ? $chunk_size = 300; // 3MB
? ? ? ? // 設(shè)置指針位置
? ? ? // fseek($fp, 0);
? ? ? ? // 開啟緩沖區(qū)
? ? ? ? ob_start();
? ? ? ? // 分段讀取文件
? ? ? ? while (!feof($fp)) {
? ? ? ? ? ? echo fread($fp, $chunk_size); //輸出數(shù)據(jù)到php緩沖區(qū)
? ? ? ? ? ? $data = ob_get_contents(); //獲取緩沖區(qū)中的內(nèi)容
? ? ? ? ? ? fwrite($newf,$data);
? ? ? ? ? ? $log = memory_get_usage()."\n"; //記錄內(nèi)存使用情況
? ? ? ? ? ? fwrite($logf,$log);
? ? ? ? ? ? ob_clean(); //刪除緩存區(qū)中的數(shù)據(jù)
? ? ? ? ? ? //ob_flush(); //刷新php緩沖區(qū)中的內(nèi)容到服務(wù)器
? ? ? ? ? // flush(); //刷新web服務(wù)器緩沖區(qū)到客戶端
? ? ? ? ? // sleep(1); // 每1秒 下載 2 MB
? ? ? ? }
? ? ? ? // 關(guān)閉緩沖區(qū)
? ? ? ? ob_end_clean();
? ? ? ? fclose($fp);
? ? ? ? fclose($newf);
? ? ? ? fclose($logf);
? ? ? ? exit();
? ? }
//通過每次讀取固定的數(shù)據(jù)存到緩沖區(qū),然后讀取緩沖區(qū)的數(shù)據(jù)寫入文件后清空緩沖區(qū)來達(dá)到控制使用內(nèi)存大小的結(jié)果。讓下載大文件數(shù)據(jù)時(shí)不會(huì)導(dǎo)致內(nèi)存溢出。還可以通過sleep函數(shù)來限制下載的速率?