PHP / Javascript:如何限制下载速度?
我有以下情况:
您可以从我们的服务器下载一些文件.如果您是“普通”用户,则您的带宽有限,例如500kbits.如果您是高级用户,您的带宽没有限制,可以尽快下载.但是我怎么能意识到这一点? 如何上传&合作?
注意:您可以使用
PHP执行此操作,但我建议您让服务器本身处理调节.这个答案的第一部分涉及你的选择是什么,如果你想限制PHP的下载速度,但下面你会发现几个链接,你会发现如何管理下载限制使用服务器.
有一个PECL扩展,这使得这是一个非常简单的任务,称为pecl_http,其中包含函数 $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 我从来没有限制自己的下载速度,但是看着这些链接,我认为很简单,说nginx是最简单的: location ^~ /downloadable/ { limit_rate_after 0m; limit_rate 20k; } 这使得速率限制立即启动,并将其设置为20k.详情可在the nginx wiki找到. 就apache而言,这并不是那么难,但是它需要你启用鼠标模块 LoadModule ratelimit_module modules/mod_ratelimit.so 然后,告诉apache哪个文件应该被限制是一个简单的事情: <IfModule mod_ratelimit.c> <Location /downloadable> SetOutputFilter RATE_LIMIT SetEnv rate-limit 20 </Location> </IfModule> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |