[英]Limit download speed using PHP
我在 Google 上找到了一些 PHP 腳本來限制文件的下載速度,但文件下載速度為 10 Mbps,或者如果按照我的設置以 80 kbps 的速度下載,則在 5 mb 后,它會停止下載。
有人可以告訴我在哪里可以找到一個好的 PHP 下載限速腳本嗎?
非常感謝你
- - 編輯 - -
這是代碼:
<?php
set_time_limit(0);
// change this value below
$cs_conn = mysql_connect('localhost', 'root', '');
mysql_select_db('shareit', $cs_conn);
// local file that should be send to the client
$local_file = $_GET['file'];
// filename that the user gets as default
$download_file = $_GET['file'];
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 85;
if(file_exists($local_file) && is_file($local_file)) {
// send headers
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
// flush content
flush();
// open file stream
$file = fopen($local_file, "r");
while(!feof($file)) {
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
// close file stream
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
if ($dl) {
} else {
header('HTTP/1.0 503 Service Unavailable');
die('Abort, you reached your download limit for this file.');
}
?>
下載 5MB 后停止的原因是因為以 80KB/s 的速度下載 5MB 需要 60 多秒。 大多數“限速器”腳本使用sleep()
在發送一個塊后暫停一段時間,恢復,發送另一個塊,然后再次暫停。 但是如果腳本已經運行了一分鍾或更長時間,PHP 會自動終止它。 發生這種情況時,您的下載會停止。
您可以使用set_time_limit()
來防止您的腳本被終止,但某些 Web 主機不允許您這樣做。 在這種情況下,你就不走運了。
一秒鍾時間太長,會讓客戶端認為服務器沒有響應,提前結束下載。 將sleep(1)
更改為usleep(200)
:
set_time_limit(0);
$file = array();
$file['name'] = 'file.mp4';
$file['size'] = filesize($file['name']);
header('Content-Type: application/octet-stream');
header('Content-Description: file transfer');
header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
header('Content-Length: '. $file['size']);
$open = fopen($file['name'], 'rb');
while( !feof($open) ){
echo fread($open, 256);
usleep(200);
}
fclose($open);
我嘗試了一個自定義類,可以幫助您處理限速下載,您可以嘗試以下方法嗎?
class Downloader {
private $file_path;
private $downloadRate;
private $file_pointer;
private $error_message;
private $_tickRate = 4; // Ticks per second.
private $_oldMaxExecTime; // saving the old value.
function __construct($file_to_download = null) {
$this->_tickRate = 4;
$this->downloadRate = 1024; // in Kb/s (default: 1Mb/s)
$this->file_pointer = 0; // position of current download.
$this->setFile($file_to_download);
}
public function setFile($file) {
if (file_exists($file) && is_file($file))
$this->file_path = $file;
else
throw new Exception("Error finding file ({$this->file_path}).");
}
public function setRate($kbRate) {
$this->downloadRate = $kbRate;
}
private function sendHeaders() {
if (!headers_sent($filename, $linenum)) {
header("Content-Type: application/octet-stream");
header("Content-Description: file transfer");
header('Content-Disposition: attachment; filename="' . $this->file_path . '"');
header('Content-Length: '. $this->file_path);
} else {
throw new Exception("Headers have already been sent. File: {$filename} Line: {$linenum}");
}
}
public function download() {
if (!$this->file_path) {
throw new Exception("Error finding file ({$this->file_path}).");
}
flush();
$this->_oldMaxExecTime = ini_get('max_execution_time');
ini_set('max_execution_time', 0);
$file = fopen($this->file_path, "r");
while(!feof($file)) {
print fread($file, ((($this->downloadRate*1024)*1024)/$this->_tickRate);
flush();
usleep((1000/$this->_tickRate));
}
fclose($file);
ini_set('max_execution_time', $this->_oldMaxExecTime);
return true; // file downloaded.
}
}
我已將文件作為要點托管在 github 上。 - https://gist.github.com/3687527
下載器類很好,但是如果您同時下載兩次,則有一個問題,您將丟失max_execution_time
值。
一些例子:
下載第一個文件(大小 = 1mb;下載時間 100 秒)
一秒后下載第二個文件(大小 = 100 mb;下載時間 = 10000 秒)
首先下載設置max_execution_time
為 0
第二次_oldMaxExecTime
為 0
第一次下載結束並返回max_execution_time
到舊值
第二次下載結束並返回max_execution time
為 0
試試這個: http : //labs.easyblog.it/download-limiter-php/
使用 pv unix 命令以獲得最佳帶寬精度
首先max_execution_time
是腳本的執行時間。 睡覺不是其中的一部分。
關於速度限制,您可以使用令牌桶之類的東西。 我已經把所有東西都放在一個方便的庫中: bandwidth-throttle/bandwidth-throttle
use bandwidthThrottle\BandwidthThrottle;
$in = fopen(__DIR__ . "/resources/video.mpg", "r");
$out = fopen("php://output", "w");
$throttle = new BandwidthThrottle();
$throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s
$throttle->throttle($out);
stream_copy_to_stream($in, $out);
這段代碼對我有用
<?php
$file_to_download = '1.mp3';
$client_file = '1.mp3';
$download_rate = 200; // 200Kb/s
$f = null;
try {
if (!file_exists($file_to_download)) {
throw new Exception('File ' . $file_to_download . ' does not exist');
}
if (!is_file($file_to_download)) {
throw new Exception('File ' . $file_to_download . ' is not valid');
}
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($file_to_download));
header('Content-Disposition: filename=' . $client_file);
// flush the content to the web browser
flush();
$f = fopen($file_to_download, 'r');
while (!feof($f)) {
// send the file part to the web browser
print fread($f, round($download_rate * 1024));
// flush the content to the web browser
flush();
// sleep one second
sleep(1);
}
} catch (\Throwable $e) {
echo $e->getMessage();
} finally {
if ($f) {
fclose($f);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.