Header issue in PHP
I remember back in the days when I was new to PHP, was so strange to why I can’t do echo before header.
Then I started googling
about this topic.
Basically, when you send body content to the browser before sending your header content with the header()/setcookie()/setrawcookie() methods, you wiil get an error message “Cannot modify header information – headers already sent”.
This is because the HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.
The output buffering solves this issue. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
By default the output buffering is disabled in php.ini file. There are two ways of enabling output buffering,
1. Enable output_buffering in php.ini
e.g. output_buffering = on
2. Call ob_start() method to turn on output buffering.
Let’s take an example, how it works :
Example :
1. Example with error
<?php
echo "Test";
setcookie('name', 'value');
?>
The above script will throw an error “Cannot modify header information – headers already sent”, only if the output_buffering is disabled in php.ini file.
2. Example without error
<?php
ob_start();// Turn on output buffering
echo "Test";
setcookie('name', 'value');
ob_end_flush(); // Flush (send) the output buffer and turn off output buffering
?>
The above script will work with zero error plus zero warning.
Reference : http://in2.php.net/manual/en/function.header.php