PHP Output Buffering

Some of the coolest functions available in PHP are the output buffering functions.  If you are reading this, you probably have some idea of how web php pages are delivered from the server to the client, but if you don’t, here is a quick recap:

  1. User requests any web page
  2. The web server receives and interprets the request
  3. The requested file is sent to the PHP processor
  4. PHP compiles and executes the combination of PHP and HTML sent to it
  5. The compiled information is sent back to the web server (the page may not be complete yet)
  6. Your browser downloads the page from the web server

That was just an overview of the process, not a detailed explanation.  Output buffering happens between step 4 and 5 (while the PHP Engine is processing the php/html before it gets sent to the browser).  Output buffering stores text or html that would normally have been sent to the server (to be sent to the browser) in a buffer.  This buffer remains available to php until either the buffer is manually closed or the php script finishes running.  The purpose of output buffering is to capture the text that should be sent to the browser in a “buffer” and store it to be manipulated by php.  Here is a simple explanation and then I will get into the specific functions.  You use output buffering in four steps:
  1. Start the Output Buffer capturing text
  2. Send text such as html or echoed strings to the browser (this will be captured by the output buffer)
  3. Optionally store the buffer in a variable or clear its contents
  4. Send the buffer to the browser
Imagine output buffering like a pair of scissors that lets you snip pages from a book and rearrange or copy them in the order you desire.
Okay, onto the functions now.  I am going to group them by related functionality.
Start the buffer
Erase the buffer
Store the buffer into a variable and/or erase it
Output the buffer to the browser
Get information about the buffer
Okay, on to what each function does.
bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )
You must always call ob_start before using output buffering with PHP.  Calling ob_start notifies php to begin to store the outputted text in the buffer.  Ob_start accepts three parameters. The first parameter is a function that will be called when the output buffer is closed.  This function will take the contents of the output buffer as its parameter and should return a string to replace the output buffer with.  I’ll show you an example shortly.  The next parameter will cause the buffer to flush (be sent to the browser) every time it gets to the specified length.  The third parameter, if set to false, will prohibit the buffer from being erased until the php script finishes.  You may stack output buffers (i.e. open another output buffer within one that is already open), capturing different parts of text from a document into different buffers.  You must remember to close the number of buffers you have opened.
string ob_gzhandlerstring $bufferint $mode )
This function is designed to compress text that is to be sent to the browser.  It is designed to be used with ob_start as a callback (i.e. a function that another function calls when it is executed).  Ob_gzhandler will determine the proper compression to send to the browser based off of the acceptable compression header the browser sends to the web server.  Gzip compressing your webpages can result in considerable bandwidth savings.
Examples

<?php
ob_start('ob_gzhandler');
echo 'Hello World';

This will gzip (compress) and send “Hello World” to the browser.  Notice I left off the closing php tag because it is not required if I do not have any HTML below it and it helps eliminate the possibility of injecting accidental whitespace into your scripts.

<?php

function strong_em( $buffer )
{
$buffer = str_replace('<strongem>', '<strong><em>', $buffer);
$buffer = str_replace('</strongem>', '</em></strong>', $buffer);
return $buffer;
}

ob_start('strong_em');
echo '<strongem>This text will be both bolded and italicized</strongem>

This is one of the more useful implementations of output buffering.  It allows you to create custom html tags and convert them into actual html tags.  (Don’t forget to make sure your tags are nested properly however) The actual output of that would be:

<strong><em>This text will be both bolded and italicized</em></strong>

void ob_cleanvoid )

This will erase anything currently stored in the output buffer. It does not turn it off, however, so the buffer will continue to capture text.

bool ob_end_cleanvoid )

This will not only erase the content stored in the output buffer, it will also close that output buffer.  If you have several output buffers open, it will only close the top most buffer (the oldest opened buffer).

string ob_get_flushvoid )

Ob_get_flush will return the contents of the output buffer as a string.  It will then flush the buffer and end output buffering.  As a reminder, flushing the buffer sends it the the browser (it’s like echo).

string ob_get_contentsvoid )

Ob_get_contents will return the contents in the buffer as a string.  It does not erase the buffer or close it.  If you echo the variable that you stored the buffer in, and allow the buffer to flush at the end of the script, it will be displayed twice.

string ob_get_cleanvoid )

This will return the contents of the output buffer and erase its contents.  It will also end output buffering.  It is the same as calling ob_get_contents() and ob_end_clean();  This is the output buffering function I find that I use most.

ex:

	<?php
	function echoFive()
	{
		echo 'five';
	}
	ob_start(); 
	echoFive();
	$five = ob_get_clean(); // contains the string 'five'

This is a simple example, but if you are working with a function that echos information that you need to filter or store in a variable, it is an excellent way to capture that content into a variable.

bool ob_end_flush ( void )

This function will close the outer most output buffer and flush its contents to the browser (again, like echo).

void ob_flush ( void )

This function will simply flush the contents of the output buffer, the output buffer will continue to capture output after being flushed however.

int ob_get_level ( void )

Returns the current number of output buffers that are open.

int ob_get_length ( void )

Returns the number of characters in the output buffer.

array ob_get_status ([ bool $full_status =FALSE ])

Returns that status of the current output buffer.  If $full_status is set to TRUE, this function will return the status for all the output buffers, not just the current one.

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => default output handler
    [del] => 1
)

This is an example of return value from ob_get_status.

array ob_list_handlers (void)

Returns the list of callback functions passed to all the open calls to ob_start.  For example, if you have ob_start() and ob_start(’gz_handler’), you will get an array with the values of 0=>default output handler, 1=>ob_gzhandler

It is important to close all of the output buffers you open because you many not realize which buffer you are getting the information from otherwise.  However, if you call ob_start() at the begining of your PHP script, you can avoid potential white space injection issues.  If you are trying to set a header value for the return page ( or a cookie, which is set in the response header) you cannot have text sent to the browser before those calls.  If you call ob_start() before you make any of those calls, at the end of the script execution the buffer will automatically close and send the content to the browser, preventing anything from being sent to the browser until the very end of your script.

Another great use of output buffering is to gzip the content you are sending back the browser.  Just call ob_start(’ob_gzhandler’) and when the script finishes all of the content to be sent to the browser will be gzipped before being sent.  The nice thing about ob_gzhandler is that it will auto determine the type of compression (if any) the browser requesting the page can handle and return it’s output accordingly.  Just a note however – for gzipping to work, your PHP installation must have the ZLib extension intalled.

Well, that’s all I can think of for output buffering at the moment. However, if you have any questions, please send them through comments and I will not only do my best to answer them, but also make sure that I can include the information in this article.  Feel free to digg this page if it has helped.  Happy PHPing!

One Comment on PHP Output Buffering

  1. What’s new for October » Blueberryware
    October, 22nd 2008 at 8:22 pm

    [...] Email 2.0 will be using add a “lazy mode.”  Lazy mode will use output buffering to scrape the entire page for email addresses and escape them, you won’t even need to use the [...]

Leave a Reply


WP Login