The output buffering functions of php aren't well known (yet), but are nevertheless extremely useful. These functions give you more control over the output generated by your scripts than you would normally have, and in some cases, this control is essential. Not only do you have control over when, where, and why your output is displayed, but you can also control how the output is handled. In this tutorial I hope to cover the general idea behind output buffering, as well as a few common uses.
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 Tutorials :
<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 Tutorials :
<?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();
?>
Please do not take this example literally as a way to get around the error, it'd be much easier to just move the header() function to the top, or use a meta refresh, but it's the principle that I would like you to grasp. Lets break this down into small peices.
ob_start();
This function opens up a new buffer. All output of the script will be put into this buffer, so that you may act upon it later. Think of this like a giant string in which all of the output of your script will be appended to. In the previous example, the output would be "You will now be directed to google.com...".
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.
As you have noticed, you cannot do much with these two functions alone. Now comes the fun part. The Output Buffering API in php comes with some nice functions to give you a lot of control over the way you handle your scripts, Read on if you want to check these out in detail.