Output Buffering in PHP - By PHP Expert


Output Buffering in PHP

How to capture content for server-side caching in PHP.

Since version 4, PHP has supported output buffering. Output buffering allows you to have all output from a script stored in a buffer instead of having it immediately transmitted to the client.

If you wanted to capture the output of a script before output buffering, you would have to write this to a string and then echo that when the string is complete:

<?php
  $output = "<HTML><BODY>";
  $output .= "Today is ".strftime("%A, %B %e %Y");
  $output .= "</BODY></HTML>";
  echo $output;
  cache($output);
?>

If you are old enough to have learned Web programming with Perl-based CGI scripts, this likely sends a shiver of painful remembrance down your spine! If you\'re not that old, you can just imagine an era when Web scripts looked like this.

With output buffering, the script looks normal again. All you do is add this before you start actually generating the page:

<?php ob_start(); ?>

This turns on output buffering support. All output henceforth is stored in an internal buffer. Then you add the page code exactly as you would in a regular script:

HTML Code

<HTML>
<BODY>
Today is <?= strftime("%A, %B %e %Y") ?>
</BODY>
</HTML>

After all the content is generated, you grab the content and flush it:

PHP Code

 

<?php
  $output = ob_get_contents();
  ob_end_flush();
  cache($output);
?>

ob_get_contents() returns the current contents of the output buffer as a string. You can then do whatever you want with it. ob_end_flush() stops buffering and sends the current contents of the buffer to the client. If you wanted to just grab the contents into a string and not send them to the browser, you could call ob_end_clean() to end buffering and destroy the contents of the buffer. It is important to note that both ob_end_flush() and ob_end_clean() destroy the buffer when they are done. In order to capture the buffer\'s contents for later use, you need to make sure to call ob_get_contents() before you end buffering.

Using Output Buffering with header() and setcookie()

A number of the online examples for output buffering use as an example of sending headers after page text. Normally if you do this:

PHP Code

<?php
        print "Hello World";
        header("Content-Type: text/plain");
?>

You get this error:

Cannot add header information - headers already sent

In an HTTP response, all the headers must be sent at the beginning of the response, before any content (hence the name headers). Because PHP by default sends out content as it comes in, when you send headers after page text, you get an error. With output buffering, though, the transmission of the body of the response awaits a call to flush(), and the headers are sent synchronously. Thus the following works fine:

PHP Code

<?php
        ob_start();
        print "Hello World";
        header("Content-Type: text/plain");
        ob_end_flush();
?>

Select all

I see this as less an example of the usefulness of output buffering than as an illustration of how some sloppy coding practices. Sending headers after content is generated is a bad design choice because it forces all code that employs it to always use output buffering. Needlessly forcing design constraints like these on code is a bad choice.

No comments

Enter your email address:

Delivered by FeedBurner

OR

 Subscribe in a reader

 
jQuery UI provides a comprehen
 
Program Plan   I drafted a p
 
I present to you my skills, ac
 
Introduction One of the issue
 
If you are a PHP developer and
 
cURL is a great tool to help y
 
cformsII cforms is a powerful
 
  The lack of Unicode su
 
History PHP-GTK was origina
 
Performance on the web is stra
 
Listen t
 
What\'s the number one cost in
 
When you\'re discussing the In
 
Classe
 
A service-oriented architectur
 
Introduc
 
PHP Crons and Linux Linux has
 
Cross site scripting (XSS) is
 
What Makes a Web 2.0 Applicati
 
As you develop web application
 
Cryptogr
 
Posting
 
Have you
 
Resources The Google API - ht
 
Get Started
 
Output B
 
If you r
 
PHP has some really sweet new
 
There were some new php.ini di
 
In PHP 5 there are some new fu
 
The following code implements
 
The following code snippet imp
 
A fine implementation of the o
 
Exception handling PHP 5 adds
 
Support for dereferencing obje
 
Static members Classes defini
 
Explicit object cloning In or
 
final methods The final keywo
 
Interfaces Gives the ability
 
The new object oriented featur
 
Sometimes its the little thing
 
Consider your file is at locat
 
# If a method can be static, d