How to use Output Buffering in PHP

Author: Mattias (mattias@999tutorials.com)
Categories: PHP
 Output buffering is something that often is forgotten by new people in PHP. You can create really powerful things with functions like ob_start and the other. Compresse, replace and modify to mention a few.
The tutorial:

Digg this, Post to del.icio.us,

Have you heared about output buffering in PHP?

If your answer is no you are not alone. It took me atleast two years after I started to use PHP until I found that functions and understood what to use it for.

First I'll try to explain what Output Buffering does

The main reason output buffering in PHP is not know by everyone might be that it's a little bit hard to understand what it's good for :-) Pretty straight forward explanation is that with this functionallity you can catch all output before the user sees it. Why you might ask... The answer is because... you can modify it in certain ways for your need.

Stupid example for explaining, but never use this :) 

Examples is the best way to understand things... so here goes a very simple and stupid example, just to get you to understand WHAT outputbuffering does, and then after this we will talk about what GOOD things it can be used for.

<?
ob_start("ourCallbackFunction");
echo "Hi I am a banana and I want to be an orange";
ob_end_flush();

function outCallbackFunction($theBuffer)
{
   $theBuffer = str_replace("banana", "skateboard", $theBuffer);
   return $theBuffer;
}
?>

This code has got some things that are important and that is the two functions that are marked bold: ob_start and on_end_flush. ob_start makes sure that PHP holds back all output without showing anything for the use (until the script is ended or the function ob_end_flush is called). The difference between this and how a script normally is working is that normally everything that is echo:ed is displayed for the used directly.

The next important thing is the parameter passed to ob_start. The parameter is telling PHP to call the function with that name when it's gonna flush everything and show it to the user. In this case the function replaces all words "banana" with the name word "skateboard". So the output will be "Hi I am a skateboard and I want to be an orange". (I warned you that the example would be stupid, but you get the idea now I hope :-)

Now to a more useful example/tips off output buffering

Things that need to go to the http header needs to be echoed first of all in the output. Examples on that is setting cookies, setting how caching is handled and redirecting with header("location blabla.php"); Also sessions needs to be started at the evry beginning of scripts when no output has been done.

Most of the time you are able to do things like this first in your file, but not always. Let's say for example that a user is logging in and in your login script you already have called the script that writes out the beginning of your html design. How will you handle that a session is started to set the user to be logged in? You can't, but with ob_start you can :-)  If you start your login.php with the row "ob_start". Further down you check if the username and password is correct agains the database and want to start the session. That is ok now, because no output has been passed to the user. Magic :-) Just set the session-data and you can also do a nice header("Location: loggedin.php"); exit; to pass the user to a page only for logged in users. If username was not correct you just echo that as usual and at the end of your script you call ob_end_flush and everything is displayed to the user.

Making your session parameter XHTML valid with output buffer

You might know that the letter & is not a valid XHTML character, and it should always be converted to &amp; When you start a session, in some configurations your urls will look like this <a xhref=index.php?action=view&PHPSESSID=33d5f200dffdf343224"> because that is a way of passing the PHPSESSION-id on to the next page. With this small callback you can make that url XHTML valid :-)

function callback($buffer)
{
  $buffer = str_replace("&PHPSESSID", "&amp;PHPSESSID", $buffer);
  return $buffer;
}

Pretty simple it takes the text going to the user and replaces &PHPSESSID with &amp;PHPSESSID. This way you have made your browser much more happy!

 

I will not give you more examples, but ideas that you can implement with output buffer techinques is compression of all output with gz to save bandwidth. You can pass your css via a outputbuffer and remove characters that are not important like whitespaces.

If you want to read more about outputbuffering go here to read about it at PHP.net


Digg this, Post to del.icio.us,
 


eXTReMe Tracker