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

WBOY
풀어 주다: 2016-07-25 09:04:33
원래의
1388명이 탐색했습니다.
  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. ?>
复制代码

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



원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!