File download with speed limit


 / Published in: PHP
 

URL: http://jonasjohn.de/snippets/php/dl-speed-limit.htm

This snippet shows you how to limit the download rate of a file download.

  1. // local file that should be send to the client
  2. $local_file = 'test-file.zip';
  3. // filename that the user gets as default
  4. $download_file = 'your-download-name.zip';
  5.  
  6. // set the download rate limit (=> 20,5 kb/s)
  7. $download_rate = 20.5;
  8. if(file_exists($local_file) && is_file($local_file)) {
  9. // send headers
  10. header('Cache-control: private');
  11. header('Content-Type: application/octet-stream');
  12. header('Content-Length: '.filesize($local_file));
  13. header('Content-Disposition: filename='.$download_file);
  14.  
  15. // flush content
  16. flush();
  17. // open file stream
  18. $file = fopen($local_file, "r");
  19. while(!feof($file)) {
  20.  
  21. // send the current file part to the browser
  22. print fread($file, round($download_rate * 1024));
  23.  
  24. // flush the content to the browser
  25. flush();
  26.  
  27. // sleep one second
  28. sleep(1);
  29. }
  30.  
  31. // close file stream
  32. fclose($file);}
  33. else {
  34. die('Error: The file '.$local_file.' does not exist!');
  35. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: x-phile on December 16, 2009

I am writing code for file download with speed limitation as was described below. Using sleep in file data sending loop causes browser to hang - it waits for file but download don't starts. If I comment sleep statement - all works. What could be the problem? System: Debian squeeze 2.6.31.6, Apache 2.2.14-3, PHP 5.2.11

You need to login to post a comment.