So every once in a while I want/need to write some code that may take some time to execute. The problem is because it takes so long to execute, I need to make sure to give the user some feedback during this process so they know the page is working. If I hit submit in a page and nothing changes in my screen after 20-30 seconds I assume something is wrong. For example, I wrote a php page that would query multiple users in one db, then for each user load their xml data from another db and parse out the information to return a report for all users in the date range. Depending on the date range, this could take a few minutes to complete. This is where the php output buffer comes into play.

The idea is you start the output buffer with the php ob_start() function,  print/echo stuff to the browser (but it won’t be displayed since it’ll be kept in the buffer), finally flush the buffer so it send it’s contents to the browser. You repeat this each time you want something displayed in the browser. Here’s an example, it’s very similar to the examples you can find the the php.net manual covering output buffers.

<?php
 
// start output buffer
if (ob_get_level() == 0) ob_start();

for($i=0;$i<70;$i++)
{
    echo ‘printing…<br />’;
    print str_pad(,4096)."\n";
    
    ob_flush();
    flush();
    usleep(30000);

    // depending on what you are doing, you may or may not need this
    set_time_limit(30)

}
 
?>

First you start the buffer, then loop 70 times and echo a str. I had to add the str_pad() part to make this work on Google Chrome and I won’t try to act like I can explain why… I probably read it somewhere :p. Then we do ob_flush() and flush(), both are needed for this to work. For this example a usleep() call was added to make each page take a little bit longer to execute so we can see this example work. Finally, not needed for this example, but was needed for my report since it took so long to execute – set_time_limit(). I believe the php’s default time limit for executing a page is 30 seconds, anything over that and you will get a php error saying your script is taking too long and has been stopped. To solve this, I reset my timer to 30 seconds on every loop since each call shouldn’t take more than 30 seconds. You can set the time limit to never expire but that could be bad and I wouldn’t recommended.

That’s all the code you need to make this example work. Depending on what you are working on: start the buffer, then just print/echo whatever needed and flush to display on the screen then continue to the next loop/section. If you have any questions, comments, better ways of doing this, or improvements please feel free to comment!