php force echo output to browser while page is still loading

Posted on at


Hello,

This post is very brief and a quick tip.

In this age where Ajax has taken over as preferred method for background tasks there are many a time that we still have heavy ended loops that holds the page load till they finish their execution. Well! normal scenarios is when we do reports stuff.


So your script will look like this

 

 

But as per some reports such as this one

bugs.php.net/bug.php?id=23877

The above method may not work. But the one that I use is the one given below

Preferred way


 

 

As you can see that I’ve called ob_start() as the first line of above example. ob_start() will enable the output buffering for our page.

Then you see that I am using function ob_end_flush() and flush() after the echo function.

This means that whatever is in the current output buffer, flush it.

Thus whatever is printed will appear on your browser.

Excercise

Copy paste this code into a new file called test.php and save it to the root of your test website’s root folder and then run it from browser to see if it works.


 

 

Lot of people would have loads of problems with this stuff. Its your webserver that has to be set correctly and even then the code above may not work.

If the above does not work then its work add the header to the start of the script as shown below


 

 

Above should print 0 till 9 and with each increment you will notice a delay of 1 second.

I hope this helps.



About the author

160