Hey everyone. I was reading about output buffering for php and have noticed that enabling it requires more resources, and that for sure slows down websites due to more cpu load and data transfer between the client and server. I checked the php.ini config file and it turned out that output buffering was on. I turned it off, reloaded the website page and got an error with the header: headers already sent. Should I remodify my code so that no information goes to the output before calling the header? Is there an alternative? Thanks for any replies.
Yes you should never send anything before the headers. Even space before the php tag can count as something, so watch that... But I'm surprized output buffering would be a resource drag. I'm sure it will use a little more ram to store the page but I dont think it's significant. Btw you can use output buffering inside your code by using the ob_ finctions (ob_start(), etc.). It's the first time I hear about it being set in php.ini. I'm curious to learn what this setting exactly does.
I see, but what about the following example:
if($i=='1')
{
 echo "User chose option 1";
}
elseif($i=='2')
{
 header(Location: page2.php);
 exit;
}
else
{
 header(Location: defaultpage.php);
 exit;
}
Will this create a problem with the header?
No, why would it create a problem? , are you executing any header related code before the conditionals you showed in the example?
@MrClass: PHP is literal. You will not get any errors for sure (and the interpreter will not parse ahead and prove that your code would or would not emit output before the header). So no, it's not the "position" of the header function that matters. Rather, it's its position in time while executing the request that matters.
@MrClass: There is something fundamentally wrong with your PHP installation. Output buffering is used make things faster. In fact, output buffering is used everywhere and not just to "buffer" output. This is a quote from TuxRadar:
Without output buffering, PHP sends data to your web server as soon as it is ready - this might be line by line or code block by code block. Not only is this slow because of the need to send lots of little bits of data, but it also means you are restricted in the order you can send data. Output buffering cures these ills by enabling you to store up your output and send to send it when you are ready to - or to not send it at all, if you so decide.
TuxRadar has an invaluable tutorial on PHP, called Practical PHP. Link for the output buffering chapter, please memorize it :P.

It also allows you to have complete control of the entire data sent to the client. You could have the entire buffer in a variable and you can manipulate it the way you desire.

Part I. Part II