Sunday, August 31, 2014

Turn PHP Output Buffer Off to Make it Live on IIS


Questions will be raised on why we need such a trivial feature on our machines? The answer is simple, we want to turn our browser into a server console. When we deal with a extremely large database and we use PHP to process it, we really need the live update on the browser to see the progress as it may take a few hours to complete. Especially when it comes to debugging the PHP during the MySQL processing, any problem will be immediately spotted if it is being run live. If not, you may only realize there is a bug in your program hours later. Then you need to wait for a few more hours to find out more about the outcome again. Live update of browsers will come in handy for cases like I mentioned.

The method:

Change two things in php.ini in c:\Program Files (x86) folder.

1. output_buffering = Off
2. max_execution_time = 0

NOW REMEMBER TO REBOOT YOUR PC!





There are a lots of recommendations on the web such as changing certain values in IIS (PHP-CGI) and using flush() or ob_flush() in PHP. I've tried them. They don't work.

However, the following codes need to be used to clear the buffer before the PHP can become live:


<?php

ob_implicit_flush();
header("Content-Type: text/html");

for ($i=0; $i < 4150; $i++) {
  echo ' ';
}

// The following is not needed as it is just to make sure your PHP can go live.

for($i=0; $i < 5; $i++){
  echo $i . '<br>';
  sleep(1);
}

?>



Why 4150? I've done some testings on two machines and it seems that the number has to be more than 4096 (default buffer size). 4150 seems to be OK on both machines although one machine can go as low as 4130.



If you running PHP on IIS, you'll need to set your IIS to allow the execution of PHP to run longer. Here are the steps to set the IIS (Windows 7):


Start->My Computer (Right Click)


IIS->FastCGI Settings


Double Click on the FastCGI exe file or right click -> Edit.




Set the Activity and Request Timeout value to higher number (in seceonds).

Restart your PC.

1 comment: