Download File with a Speed Limit in PHP


/ Published in: PHP
Save to your folder(s)

This snippet allows you set a limitation for download rate of the file that visitors download from your site.


Copy this code and paste it in your HTML
  1. <?php
  2. /* set here a limit of downloading rate (e.g. 10.20 Kb/s) */
  3. $download_rate = 10.20;
  4.  
  5. $download_file = 'download-file.zip';
  6. $target_file = 'target-file.zip';
  7.  
  8. if(file_exists($download_file)){
  9. /* headers */
  10. header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
  11. header('Cache-control: private');
  12. header('Content-Type: application/octet-stream');
  13. header('Content-Length: '.filesize($download_file));
  14. header('Content-Disposition: filename='.$target_file);
  15.  
  16. /* flush content */
  17. flush();
  18.  
  19. /* open file */
  20. $fh = @fopen($download_file, 'r');
  21. while(!feof($fh)){
  22. /* send only current part of the file to browser */
  23. print fread($fh, round($download_rate * 1024));
  24. /* flush the content to the browser */
  25. flush();
  26. /* sleep for 1 sec */
  27. sleep(1);
  28. }
  29. /* close file */
  30. @fclose($fh);
  31. }else{
  32. die('Fatal error: the '.$download_file.' file does not exist!');
  33. }
  34. ?>

URL: http://www.apphp.com/index.php?snippet=php-download-file-with-speed-limit

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.