views:

47

answers:

3

How to limit speed of outgoing response from php script? So I have a script generating data in keep-alive connection. It just opens file and reads it. How to limit outgoing speed

(By now i have such code)

if(isset($_GET[FILE]))
 {
  $fileName = $_GET[FILE];
  $file =  $fileName;

  if (!file_exists($file))
  {
   print('<b>ERROR:</b> php could not find (' . $fileName . ') please check your settings.'); 
   exit();
  }
  if(file_exists($file))
  {
   # stay clean
   @ob_end_clean();
   @set_time_limit(0);

   # keep binary data safe
   set_magic_quotes_runtime(0);

   $fh = fopen($file, 'rb') or die ('<b>ERROR:</b> php could not open (' . $fileName . ')');
   # content headers
   header("Content-Type: video/x-flv"); 

   # output file
   while(!feof($fh)) 
   {
     # output file without bandwidth limiting
     print(fread($fh, filesize($file))); 
   } 
  } 
 }

So what shall I do to limit speed of response (limit to for example 50 kb/s)

+2  A: 

Change your file output to be staggered rather that outputting the whole file in one go.

# output file
while(!feof($fh)) 
{
    # output file without bandwidth limiting
    print(fread($fh, 51200)); # 51200 bytes = 50 kB
    sleep(1);
}

This will output 50kB then wait one second until the whole file is output. It should cap the bandwidth to around 50kB/second.

Even though this is possible within PHP, I'd use your web-server to control the throttling.

Ben S
`flush`ing the buffer after printing will ensure a steady stream of writes every second, though isn't strictly necessary.
Chadwick
please add right comments and flush so to consider this answer fully true.
Blender
A: 

You can read n bytes and then use use sleep(1) to wait a second, as suggested here.

igorw
+1  A: 

I wouldn't use php to limit the bandwidth:

For Apache: Bandwidth Mod v0.7 (How-To - Bandwidth Limiter For Apache2)

For Nginx: http://wiki.nginx.org/NginxHttpCoreModule#limit_rate

For Lighttpd: http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs:TrafficShaping This even allows you to configure the speed per connection in PHP

jigfox