Generally you print out or echo HTML code in your PHP script. So they are sent to the browser piece by piece or line by line as soon as the script parsing is complete. You don’t have control over the order you can output to the client browser. Also it is slow as it sends chunks of data one by one instead of sending the whole output at once. These problems can be solved by using output buffering.

What is output buffering?

It is a process of storing the generated output in a buffer instead of directly outputting to the client or to the browser . At the end of the script the buffer value can be sent to the client or we can prevent it if we want. We have the control over what to do with the stored buffer value.

How to use output buffering in PHP?

Output buffering can be enabled globally for all PHP scripts by setting output_buffering=on in php.ini file. Also you can enable output buffering for particular scripts you like without enabling it globally. You will need to use few functions provided by PHP. Consider the below code:

In the above code, ob_start() starts output buffering in the script. Anything you echo out in the script afterwards is stored in the buffer.

At the end of the script the stored buffer value is sent to the client using ob_end_flush(). Even if you do not use this function, at the end of the script the stored buffer value will be output to the client.

If you do not want to send the buffer value to the client you can use ob_end_clean(). This will end the buffer without outputting to the client. To get the stored buffer value before ending the buffer, you can use ob_get_contents().

What if you want to output to the browser without ending the buffer ? Well, in that case you can use ob_flush() . It will output to the browser where called, but will not end the buffer. The buffer contents will be discarded after ob_flush() is called.

Ok, now you know general usage of output buffering. You can view some more functions that PHP provides in the manual at http://www.php.net/manual/en/ref.outcontrol.php.

What are the advantages of using output buffering?

  • It will decrease the time it takes to download page as contents will be send at once instead of chunks of data.
  • You can avoid the “Warning: Cannot modify header information – headers already sent by (output)” error. If you output content before headers are sent to the browser, you will get this error. But by using out buffering, content is not directly sent to the browser instead it is sent at the end of the script and by that time header information if any would have finished reaching the browser and you will not encounter the problem.
  • You can use compressions like gzip if you wish in your script.
  • You can process and manipulate the whole content like you process a string as you can store the full content inside a single variable.

Above are few cases where you can use output buffering. This concludes the short introduction to using output buffering PHP.