php限制下载速度的实现方法

原创
2016-07-25 09:04:33 980浏览
  1. /**

  2. desc:限制下载速度
  3. link:bbs.it-home.org
  4. date:2013/2/25
  5. */
  6. // local file that should be send to the client
  7. $local_file = 'test-file.zip';
  8. // filename that the user gets as default

  9. $download_file = 'your-download-name.zip';
  10. // set the download rate limit (=> 20,5 kb/s)

  11. $download_rate = 20.5;
  12. if(file_exists($local_file) && is_file($local_file)) {

  13. // send headers
  14. header('Cache-control: private');
  15. header('Content-Type: application/octet-stream');
  16. header('Content-Length: '.filesize($local_file));
  17. header('Content-Disposition: filename='.$download_file);
  18. // flush content

  19. flush();
  20. // open file stream

  21. $file = fopen($local_file, "r");
  22. while (!feof($file)) {
  23. // send the current file part to the browser
  24. print fread($file, round($download_rate * 1024));
  25. // flush the content to the browser
  26. flush();
  27. // sleep one second
  28. sleep(1);
  29. }
  30. // close file stream
  31. fclose($file);
  32. }
  33. else {
  34. die('Error: The file '.$local_file.' does not exist!');
  35. }
  36. ?>
复制代码

附:修改Discuz论坛实现对附件下载的限速

研究了一下Discuz的代码,实现了一个可行的方案。 很简单,找到attachment.pnp,找到最下面,有个: function getlocalfile($filename, $readmod = 1, $range = 0)

修改为:

  1. function getlocalfile($filename, $readmod = 1, $range = 0) {

  2. if($fp = @fopen($filename, 'rb')) {
  3. @fseek($fp, $range);
  4. $download_rate = 10; //限制网速10kb/s
  5. while(!feof($fp))
  6. {
  7. print fread($fp, round($download_rate * 1024));
  8. flush();
  9. ob_flush();
  10. sleep(1);
  11. }
  12. }
  13. @fclose($fp);
  14. @flush(); @ob_flush();

  15. }
  16. ?>
复制代码

经过测试,发现效果还是很明显的。



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。