Friday, February 19, 2010

Using Output Buffering in PHP

By default, anything that a PHP script prints or any HTML outside of the PHP tags(even in include files) is immediately sent to the Web browser. Output buffering is a PHP feature that overrides this behavior. Instead of immediately sending HTML to the Web browser, that output is placed in a buffer-temporary memory. Then, when the buffer if flushed, it is sent to the Web browser. There can be performance benefits with output buffering, but the main benefit is that it eliminates those headers already sent error messages.

Some functions such as header(),setcookie(), and session_start() can only be called if nothing has been sent to the Web browser. Without output buffering, nothing is sent to the Web browser until the end of the page. As such, you can call these functions at any point in a script.

To begin output buffering, use the ob_start() function. This should be at the beginning of your script right after the opening PHP tag. Once this function is called, every echo() and similiar function will send data to a memory buffer rather than to the Web browser. And, HTTP calls such as header() and setcookie() will not be buffered and operate as usual.

At the end of your script, call the ob_end_flush() function to send the accumulated buffer to the Web browser. This has the effect of turning off the output buffering.

No comments:

Post a Comment

Get your own Widget