Output Buffering
Output Buffering:
=============
This functions give you more control over the output generated by your scripts than you would normally have. you can also control how the output is handled.
Lets begin with a common problem, and an easy way to fix it. Some of you may notice this common mistake, because a lot of the people new to php have made it:
PHP Example: (!)
<html>
<body>
<?php
echo “You will now be directed to google.com…\n”;
header(”Location: http://www.google.com”);
?>
</body>
</html>
Those of you who know your way around php a bit will know that you cannot use the header() function after there is any output. Output in this script begins with “”. The script above would result in an error of “cannot add header information, headers already sent”. Here is how to use the output buffering functions to get around this problem:
PHP Example: (!)
<?php
//start output buffering
ob_start();
?>
<html>
<body>
<?php
echo “You will now be directed to google.com…\n”;
header(”Location: http://www.google.com”);
?>
</body>
</html>
<?php
//send the contents of the buffer to the browser
ob_end_flush();
?>
ob_start();
========
This function opens up a new buffer. All output of the script will be put into this buffer
ob_end_flush():
===========
at the end you see the ob_end_flush() function. This function is used to ‘flush’ (send) data to the browser, and to close the buffer.
ob_end_clean():
============
The ob_end_clean function empties (hence ‘clean’) and then closes the buffer without sending the content to the browser.
flush
=====
This function will try to put all output in the buffer to the browser.
ob_implicit_flush
=============
This function turns explicit flushing on or off, if no flag is given as a parameter it will default as on. With ob_implicit_flush the buffer will be flushed after each call to output, and explicitly calling flush() is no longer needed.
ob_get_length
===========
This will return the length of the output buffer, or false if there is no active buffer.
ob_get_level
==========
This function returns the nesting level of the output buffering mechanism. meaning, it will return the level of nested output buffering, if you have more than one open buffer.
ob_get_status
==========
This function returns an array of either the status of currenly open buffers or FALSE.
