Home >Backend Development >PHP Tutorial >How to limit download speed in php

How to limit download speed in php

WBOY
WBOYOriginal
2016-07-25 09:04:331465browse
  1. /**

  2. desc: limit download speed
  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. ?>
复制代码

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



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn