Wednesday, October 20, 2010

PHP: flush and ob_flush example - print output to browser

UPDATE (June 4, 2011): After writing a parsing script in PHP I stumbled on a bad coding technique which kept crushing my script along with the browser (Firefox). This problem was noticed after running my script for longer than an hour. The real problem is not in time it took the script to execute but the amount of output being printed to the screen.

Problem: by using ob_flush() and flush() functions alone the script kept building the buffer size until it reached its peaked and crushed the browser.

Solution: After using echo commands to print your text use ob_get_contents() function to print whatever you have in the buffer. Then, use functions flush() and ob_flush() to discard the buffer. Keep in mind, ob_flush() does not destroy your buffer. Lastly, call the function ob_end_clean() to clean your buffer and start fresh.

Example:
ob_get_contents();
flush();
ob_flush();
ob_end_clean();

====================================================

The function flush() and ob_flush() are suppose to refresh the screen while the script is still working by outputting buffer to the browser. There are quite a lot of conditions to meet for each browser to make these functions work.

Here is how to make function flush() work without having to modify browser settings:



That's all there is to it. Just run 6 functions consecutively and your buffer will be printed to the screen.

As you can see, the page is still loading but the output is being printed on the screen every 3 seconds. This example uses Mozilla Firefox.

2 comments:

  1. why are you running behind dark shadow... can you explain me why you using the same function again and again without any logic... :)

    ReplyDelete
  2. "There are quite a lot of conditions to meet for each browser to make these functions work."

    That's why. Each browser has it's way of properly setting up the flush() function, therefore if you use technique specified above you'll notice it will work on majority of the browsers.

    If you know a better way please post I'll be glad to learn it and it will help me in the future.

    Thanks.

    ReplyDelete