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

前端之家收集整理的这篇文章主要介绍了php 文件下载速度限制的实现方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP限制文件下载速度,这个方案可能有一些缺陷,但可以参考一下,PHP限制文件下载速度,感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:
  1. /**
  2. * 限制文件下载速度
  3. *
  4. * @param
  5. * @arrange (512.笔记) jb51.cc
  6. **/
  7. // local file that should be send to the client
  8. $local_file = 'test-file.zip';
  9. // filename that the user gets as default
  10. $download_file = 'your-download-name.zip';
  11. // set the download rate limit (=> 20,5 kb/s)
  12. $download_rate = 20.5;
  13. if(file_exists($local_file) && is_file($local_file)) {
  14. // send headers
  15. header('Cache-control: private');
  16. header('Content-Type: application/octet-stream');
  17. header('Content-Length: '.filesize($local_file));
  18. header('Content-Disposition: filename='.$download_file);
  19. // flush content
  20. flush();
  21. // open file stream
  22. $file = fopen($local_file,"r");
  23. while (!feof($file)) {
  24. // send the current file part to the browser
  25. print fread($file,round($download_rate * 1024));
  26. // flush the content to the browser
  27. flush();
  28. // sleep one second
  29. sleep(1);
  30. }
  31. // close file stream
  32. fclose($file);
  33. }
  34. else {
  35. die('Error: The file '.$local_file.' does not exist!');
  36. }
  37. /*** 代码来自编程之家 jb51.cc(jb51.cc) ***/

猜你在找的PHP相关文章