2014-11-13 33 views
0

我有下載網頁下面的PHP代碼文件直接到我的Web服務器:如何在php中限制file_put_contents的速度?

function fileDownload() 

{ 

    $url = $_POST['downloadlink']; 

    $filename = $_POST['filename']; 

    $dir = "downloads/"; 

    $filepath = $dir . $filename; 

    file_put_contents($filepath, fopen($url, 'r')); 

} 

以上PHP函數可以很好地用於下載文件小於128 MB,但是,當文件大小超過128 MB,然後交通擁擠加載在我的服務器上創建,我的服務器暫時不可用,並中止所有連接。所以,我的文件下載被中止。我在考慮是否有任何方法來限制file_put_contents函數的速率,這樣即使我下載的文件大於128 MB,我的服務器也能正常工作。

+0

http://stackoverflow.com/questions/1603281/file-get-contents-and-file-put-contents-with-large-files – brandelizer

+0

上面的鏈接並沒有給出如何限制速度的解決方案'file_put_contents'功能.... – user3752033

+0

我知道,但也許你的服務器崩潰的原因... – brandelizer

回答

0

您可以註冊一個stream filter,這可能會限制比率。一個token bucket。我爲你做了所有這些:bandwidth-throttle/bandwidth-throttle

但是你可以只在流(即文件句柄)上註冊該過濾器。在file_put_contents()情況下,它必須註冊到輸入流:

use bandwidthThrottle\BandwidthThrottle; 

$in = fopen($url, 'r'); 

$throttle = new BandwidthThrottle(); 
$throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // 100KiB/s 
$throttle->throttle($in); 

file_put_contents($filepath, $in); 

如果要限制你必須要使用的例如寫在流的方法的輸出流stream_copy_to_stream()

use bandwidthThrottle\BandwidthThrottle; 

$in = fopen($url, 'r'); 
$out = fopen($filepath, 'w'); 

$throttle = new BandwidthThrottle(); 
$throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // 100KiB/s 
$throttle->throttle($out); 

stream_copy_to_stream($in, $out); 

實際上,兩種解決方案之間沒有太大的區別。兩者都將以100KiB/s讀寫。您可能需要爲該腳本調整max_execution_time


BTW。請勿使用$_POST作爲流源。