Discover & Rate New Music Check out ChartVote. Promote the music you like.


Limit File Download Speed with PHP

This PHP code will limit the download rate for a file being downloaded by a client. This is useful if you are streaming MP3s from your site and you are trying to distribute your bandwidth as evenly as possible.

For example: If you are streaming MP3s with a bitrate of 96kb then you would at the minimum only need to send 12KB/s of data to the client. Now to be safe I would send around 16KB/s to allow some buffering just in case some packets get held up somewhere.

Code

PHP:
  1. <?php
  2.  
  3. $file = "/path/to/file/test.mp3"; // path to file
  4. $speed = 16; // 16 kb/s download rate limit
  5.  
  6. header("Cache-control: private");
  7. header("Content-Type: application/octet-stream");
  8. header("Content-Length: ".filesize($file));
  9. header("Content-Disposition: filename=$file" . "%20");
  10.  
  11.  
  12. $fd = fopen($file, "r");
  13. while(!feof($fd)) {
  14.     echo fread($fd, round($speed*1024));
  15.     flush();
  16.     sleep(1);
  17. }
  18.  
  19. fclose ($fd);
  20.  
  21. ?>


One Comment

  1. Weekend Links - PHP Techniques, Regular Expressions, Ajax PageRank, PHP Downloads, Color Mathematics on November 17th, 2007

    [...] http://www.findmotive.com/2007/11/01/limit-file-download-speed-with-php/ [...]

Leave a Reply

RSS Feed



Recommended Sites