Output Buffering for Web Developers, a Beginner’s Guide
Sunday, January 25th, 2009 Tags: output-buffering
If you're not using PHP's output buffering, you should be. And if you are, you may not be using it to its potential.
In this article written specifically for web developers, I'll make a case for output buffering and show you how to get started within seconds. This article is the beginning of a series in which I'll share with you the awesome potential of output buffering.
Simple explanation of output buffering for Web developers
Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script. Can you already begin to see the performance advantages and post processing opportunities?
Advantages of output buffering for Web developers
- Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
- All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
- If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.
Here's a "hello world" of PHP output buffering
<?php // start output buffering at the top of our script with this simple command ob_start(); ?> <html> <body> <p>Hello world!</p> </body> </html> <?php // end output buffering and send our HTML to the browser as a whole ob_end_flush(); ?>
It's that simple! Just by doing this our webpages appear less choppy as they render. Now let's take it one step futher.
The next step: compress the output
In the code below, ob_start() is changed to ob_start('ob_gzhandler'). That one simple change compresses our HTML, resulting in a smaller HTML download size for most browsers.
<?php
// start output buffering at the top of our script with this simple command
// we've added "ob_gzhandler" as a parameter of ob_start
ob_start('ob_gzhandler');
?>
<html>
<body>
<p>Hello world!</p>
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
One more step further: custom post processing
In the code below, ob_start() is changed to ob_start('ob_postprocess'). ob_postprocess() is a function we define below used to make changes to the HTML before it is sent to the browser. Instead of Hello world!, the user will see Aloha world!
<?php
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
ob_start('ob_postprocess');
?>
<html>
<body>
<p>Hello world!</p>
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
// ob_postprocess is our custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Hello', 'Aloha', $buffer);
// "return $buffer;" will send what is in $buffer to the browser, which includes our changes
return $buffer;
}
?>
Bonus tip: you can set cookies at any time with output buffering on
Since HTML is not sent directly to the browser, we can set cookies anywhere in our scripts without worrying about anything. Just turn it on like we did in step 1 and voilà! No more cookie problems.
Finished for now, subscribe for more
There you have it! Three simple steps into output buffering to get you started. First we just turned it on with ob_start(), then we added automatic compression with ob_start('ob_gzhandler'), and finally we made ob_postprocess()—a custom function to modify our HTML before output.
In following articles in this series, we'll build on this tutorial with specific examples that really take advantage of some massively cool opportunities with output buffering that you can plug right into your own scripts. Stay tuned!
Tags: output-bufferingIf you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!
Article Sponsored by:
Beginning PHP and MySQL: From Novice to Professional, Third Edition offers a comprehensive introduction to two of the most prominent open source technologies on the planet: the PHP scripting language and the MySQL database server. Updated to introduce the features found in MySQLs most significant release to date, readers learn how to take advantage of the latest features of both technologies to build powerful, manageable, and stable web applications.
41 Comments
subscribe comments feedTrackbacks/Pingbacks
- AndySowards.com :: Web Development Nerdy Daily Links For 1/27/2009 | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
- Introduction to PHP Output Buffering
- 4 Fantastic PHP Output Buffering Tricks for Web Developers | Dev Tips | Become a Better Developer, One Tip at a Time.
- 30+ PHP Best Practices for Beginners : Webby Tutos
- PHP WebDeveloper :: O Caminho | The Blog of a WebDeveloper
- 30+ PHP Best Practices for Beginners | huibit05.com
- Zipsites Official Blog - Collection of Useful PHP Beginner Coding Tips
- 30+ PHP Best Practices for Beginners | Beyond Venture Design
- PHP para todos | TecnoPen
- Blake Reynolds » Blog Archive » 32 Best PHP Pratcises.
- Jeffrey Way » 7 Speed Considerations When Launching a New Site
- 120 Tips, Tricks, and Tuts from 2009 Worth your Time « Myblog's Blog
- 120 Tips, Tricks, and Tuts from 2009 Worth your Time | Tutorial51








This is probably my favorite server side article on here so far, fantastic job Brian!
Thanks man! Many more to come on this topic… stay tuned and subscribe!
Great article Brain! I have used output buffering but really only so I can redirect using header() at any time.
Didn’t realize all the speed benefits it can have.
Redirecting with the header() function anytime is another great advantage of ob that is on the same boat as the cookie issue. Thanks for pointing that out!
If you say tuned, I’ll take WAY beyond redirection in the next articles
I read in a comment on PHP.net that you don’t need to use ob_end_flush() in most cases because it is called automatically at the end of script execution.
Is this correct? Do you recommend using it or could I just use ob_start() ?
I have a handy site-wide include that I can insert ob_start() into, I’d rather not bother with ob_end_flush() (for the sake of neatness) if there’s no particular benefit…
Alex,
I always use ob_end_flush() because I don’t want to leave anything up to PHP that I don’t have to, which saves me from weird headaches
Great article. Shows how we can sometimes overlook things. The only times I’ve ever really used ob is to allow for debugging.
I’ll definately have to start implementing this.
Michael,
That’s good to hear! Stay tuned for more!
Do you have any idea on how this could be integrated with Smarty?
I believe smarty has it’s own output buffer / cache.
Sorry Ben, but I don’t have any experience with Smarty
Not modifying header information is one the advantages I got from ob. Good explanation!
It’s really a g8 opportunity to protect the html buffering before header information modification. Good Done!
Great guide, subscribed
Thanks basicsharp! We really appreciate the extra subscriber, makes all the difference to us
Great article, I never realized ob_start could be used this way as well. Already subscribed and waiting for more.
May I say I’m missing a ’subscribe’ button, this… made me think!
When you publish your dzone, will you specify that it’s PHP stuff you’re talking about? The world is a bit larger than just PHP. Thanks.
When you make a comment like that, will you first check to make sure I was the one that actually published it to dzone? Yep, wasn’t me. Thanks!
This is a good writeup. However, it could benefit from an explanation of the possible downsides to OB:
* Trading greater flexibility for more memory usage
* You lose the ability to stop processing PHP if the user disconnects while the page is still processing (see ignore_user_abort)
* The loss of ignore_user_abort opens you up to request-only DOS attacks on a processing-intensive page
Keep up the good work!
I thought of this, as a waste function at first sight but didn’t knew that its a perl. Thanks!
I used to do meta redirection when I got the header error! Now I can throw that meta tag in bin!
Subscribed as well!
Hey there!
I would like to thank you for such a nice article. It sure will help me out.
Please, keep up the good job, mate!
I’m bookmarking this and subscribing as well.
You do not really need explicit output buffering if you follow the MVC (recommended) architectural pattern. Do not put php and html together! If you are using a template engine like smarty you get the final page in a variable too.
Very good and simple tutorial about output buffering. Very well written also. I subscribed.
This is really a good article that made my concepts clear for Output Buffering !
Hey, I do like the way you have shown us how to use a function on the output. Can you write another article and show the difference between flush() and ob_end_flush(). There are some other things that confuse me about output buffering in general, and I’m sure other people would like the full tutorial. Thanks!
Great tutorial! Thanks Brian!
how to combine ob_gzhandler with ob_postprocess?
great tutorial