PHP/Javascript:我如何限制下载速度?

Mar*_*ann 11 javascript php limit

我有以下场景:您可以从我们的服务器下载一些文件.如果您是"普通"用户,则您的带宽有限,例如500kbits.如果您是高级用户,则没有带宽限制,可以尽快下载.但我怎么能意识到这一点?这是如何上传和合作的?

Eli*_*gem 6

注意:您可以使用PHP执行此操作,但我建议您让服务器本身处理限制.如果您想单独使用PHP来降低下载速度,那么这个答案的第一部分就是您的选择,但是您可以在下面找到几个链接,您可以在其中找到如何使用服务器管理下载限制.

有一个PECL扩展使得这个包含该函数的pecl_http是一个相当简单的任务http_throttle.文档包含一个如何执行此操作的简单示例.这个扩展还包含一个HttpResponse,它没有很好地记录ATM,但我怀疑它setThrottleDelay和它的setBufferSize方法应该产生所需的结果(节流延迟=> 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();
Run Code Online (Sandbox Code Playgroud)

如果您不能/不想安装它,您可以编写一个简单的循环:

$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
}
Run Code Online (Sandbox Code Playgroud)

当然,如果你这样做,不要缓冲输出:),也可能最好添加一个set_time_limit(0);语句.如果文件很大,很可能你的脚本会在下载过程中被杀死,因为它会达到最大执行时间.

另一种(可能更可取的)方法是通过服务器配置限制下载速度:

我自己从来没有限制下载率,但是看看这些链接,我认为nginx到目前为止是最简单的,这是公平的:

location ^~ /downloadable/ {
    limit_rate_after 0m;
    limit_rate 20k;
}
Run Code Online (Sandbox Code Playgroud)

这使得速率限制立即启动,并将其设置为20k.详细信息可以在nginx维基上找到.

至于阿帕奇而言,这并不是要困难得多,但它会要求你启用ratelimit模块

LoadModule ratelimit_module modules/mod_ratelimit.so
Run Code Online (Sandbox Code Playgroud)

然后,告诉apache应该限制哪些文件是一件简单的事情:

<IfModule mod_ratelimit.c>
    <Location /downloadable>
        SetOutputFilter RATE_LIMIT
        SetEnv rate-limit 20
    </Location>
</IfModule>
Run Code Online (Sandbox Code Playgroud)