我有以下场景: 您可以从我们的服务器下载一些文件。如果您是“普通”用户,您的带宽是有限的,例如 500kbits。如果您是高级用户,则没有带宽限制,可以尽可能快地下载。但是我怎么能意识到这一点呢? 这是怎么上传的?
最佳答案
注意:您可以使用 PHP 执行此操作,但我建议您让服务器本身处理节流。如果您想单独使用 PHP 限制下载速度,此答案的第一部分涉及您的选择,但在下面您会找到几个链接,您可以在其中找到如何使用服务器管理下载限制。
有一个名为 pecl_http 的 PECL 扩展使这成为一项相当简单的任务,它包含函数 http_throttle
.该文档包含一个简单示例,说明如何执行此操作。此扩展还包含 a HttpResponse
class ,它没有很好地记录 ATM,但我怀疑玩弄它的 setThrottleDelay
和 setBufferSize
方法应该会产生所需的结果( throttle 延迟 => 0.001,缓冲区大小 20 = = ~20Kb/秒)。从表面上看,这应该可行:
$download = new HttpResponse();
$download->setFile('yourFile.ext');
$download->setBufferSize(20);
$download->setThrottleDelay(.001);
//set headers using either the corresponding methods:
$download->setContentType('application/octet-stream');
//or the setHeader method
$download->setHeader('Content-Length', filesize('yourFile.ext'));
$download->send();
如果你不能/不想安装它,你可以编写一个简单的循环:
$file = array(
'fname' => 'yourFile.ext',
'size' => filesize('yourFile.ext')
);
header('Content-Type: application/octet-stream');
header('Content-Description: file transfer');
header(
sprintf(
'Content-Disposition: attachment; filename="%s"',
$file['fname']
)
);
header('Content-Length: '. $file['size']);
$open = fopen($file['fname'], "rb");
//handle error if (!$fh)
while($chunk = fread($fh, 2048))//read 2Kb
{
echo $chunk;
usleep(100);//wait 1/10th of a second
}
当然,如果您这样做,请不要缓冲输出 :),最好也添加一个 set_time_limit(0);
语句。如果文件很大,您的脚本很可能会在下载中途被杀死,因为它达到了最大执行时间。
另一种(可能更可取)方法是通过服务器配置限制下载速度:
- using NGINX
- using Apache2
- using MS IIS (要么安装比特率节流模块,要么设置最大带宽)
我自己从未限制过下载速率,但查看链接后,我认为可以公平地说 nginx 是迄今为止最简单的:
location ^~ /downloadable/ {
limit_rate_after 0m;
limit_rate 20k;
}
这会立即启动速率限制,并将其设置为 20k。详情可以在the nginx wiki上找到.
就 apache 而言,它并不难得多,但它需要您启用 ratelimit 模块
LoadModule ratelimit_module modules/mod_ratelimit.so
然后,告诉 apache 哪些文件应该被限制是一件简单的事情:
<IfModule mod_ratelimit.c>
<Location /downloadable>
SetOutputFilter RATE_LIMIT
SetEnv rate-limit 20
</Location>
</IfModule>
关于javascript - PHP/JavaScript : How I can limit the download speed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525273/