Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use case for output buffering as the correct solution to "headers already sent"

I see (not just on this site) a lot of question from inexperienced PHP programmers about the infamous "headers already sent... output started at" error, and many people suggest using ouput buffering as a solution.

In my experience I have never found a situation where that error wasn't caused by a flaw in the program's logic. Are there cases where output buffering is actually the correct solution?

like image 402
Matteo Riva Avatar asked May 27 '10 08:05

Matteo Riva


2 Answers

I would concur with your initial statement. Generally, solving "headers" problem with output buffering is a stopgap measure.

The really sad/funny part of this solution is: what happens when you want to output something large, such as a file you are keeping behind a paywall? Usually it results in people replacing the "headers" problem with their scripts running out of memory.

Whoops.

like image 59
ivans Avatar answered Nov 09 '22 09:11

ivans


The only situation I can imagine is a CMS or Weblog in which plugins can be invoked in the HTML code, like

<h1>My images</h1>
{plugin:show_images}

those plugins may have to add their own style sheets and other things that go in the <head> section of the page. Using buffering, this would be possible.

In practice though, this is not good for performance, feels kludgy and doesn't work when output buffering is turned off. Even here, it is therefore better to pre-process the contents before showing them, and doing any adding of style sheets etc. before anything is output.

like image 2
Pekka Avatar answered Nov 09 '22 10:11

Pekka