Falling off the ob_start stack

Pascal Hakim
Pascal is the Online Director at IDG Australia. With his team, he makes sure that the servers, code and ads that you can see on this page are all doing what they are supposed to. So please let him know if things are broken.

Recursive output buffering is a great tool in web-oriented programming, but it can go _really_ wrong.

Caleb and I spent a large chunk of yesterday finding out a bunch of bugs that had been caused by incorrect use of output buffering.

PHP lets you call some commands called ob_start and ob_get_clean, which let you buffer content and save it into a variable. This is great as it allows you to do use the templating abilities to PHP to place output in variables. This lets you do things like:


function my_output($name) { ob_start(); ?>

Hi , how's it going today?

What had happened in our case however, was that functions of the form:


function my_output($blah) {
  ob_start();
  really_long_function_call();
  return ob_get_clean();
}

Had been turned into:


function my_output($blah) {
  ob_start();
  if($cache = cached('really_long_function_call') {
    return $cache;

really_long_function_call(); return ob_get_clean(); }

The ob_start() stack was now out of whack. Whenever the top level layout code then tried to close an ob_start(), it would actually close the level that had been started in my_output(), which would cause page elements to show up out of order.

To make things more interesting, when PHP reaches the end of a program, it closes all open buffers and flushes their output out to its output. This really through us off as we spent the first hour of debugging into looking why the buffered output was being flushed when it shouldn't, when this actually wasn't happening.

This is one of those standard cases that when you suspect the bug is in the system libraries instead of your code, you're probably doing something wrong.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
Users posting comments agree to the TechWorld comments policy.
Login or register to link comments to your user profile, or you may also post a comment without being logged in.

Twitter Feed

  • rohan_p RT @Techworld_AU: Gear and gadgets at @CeBITAUS 2012, Sydney http://t.co/J1Sch1sX #cebit2012
  • Techworld_AU Gear and gadgets at @CeBITAUS 2012, Sydney http://t.co/J1Sch1sX #cebit2012
  • HamishBarwick CeBIT 2012: Will NBN speed up freight delivery times? http://t.co/gaZyjOlH #cw #cio #tw #CeBIT2012 #nbn
  • HamishBarwick CeBIT 2012: NAB calls for mobile app security overhaul http://t.co/3Z3ZPUPq #cw #cio #tw #CeBIT2012 #infosec
  • rohan_p RT @Techworld_AU: BigPond Games Arena, Games Shop hit by hackers http://t.co/OXNPeDfL #bigpond #infosec #security