Output Buffers Are too Cool

All php developers have been there. You’ve got the page working just like it should. And with one exception, it looks good too.

That exception: All of your status and debut messages. You hate to get rid of it. It’s got lots of useful information that you wouldn’t mind seeing every time you hit the page. But you know that it would make users throw up their hands in frustration. Worse yet, it might give away enough information to let a hacker do some unpleasant things on your site.

You can go through and comment out each print statement, and that’s exactly how I’ve normally handled it.

But this week, I came up with something better.

[/crayon]

The output buffer is a wonderful php construct. It starts with the function call “ob_start();”. From here, all of the printed output goes to the output buffer instead of to the user’s screen.

Presumably the routine to generate the content prints all of my ongoing statuses, and for me, it’s probably full of “print_r($Array);” calls — the php developer equivalent of windows developers inspect variable frames.

“ob_get_contents()” lets you use the contents of the output buffer, and “ob_end_clean()” clears it all out.

In this example, I use the session variable for ‘user’ (which, of course, had been set somewhere earlier in the page) to make that output buffer information print if it’s me who is logged into the site. Otherwise, the user doesn’t see it.

It also makes a lot of sense to use this to write debug information to a file.

[/crayon]

Posted in php, Web Apps | Tagged , , , , | Leave a comment

Comments are closed.