This function tells us about the status of headers. If output is posted to browser then we should not use header functions like redirect etc. To avoid such errors we can check status of headers by using headers_sent() function. It returns TRUE or FALSE based on the status of the header.
When we execute a php script the outputs are stored in buffer before sending them to browser. However it also depends on your server php.ini setting where output buffer has to be on or off.
output_buffering = Off
Now since output buffering is off so all output will be posted to browser. Let us learn by one example.
<?Php
echo 'Hello plus2net';
echo "<br><br>";
if (!headers_sent()) {
echo " No header sent , so you can use PHP to redirect ";
}else{
echo " Header already sent, so use JavaScript to redirect ";
}
?>
The output of above code will depend on your php.ini setting. For us our php.ini says like this .
output_buffering 4096 4096
In the above code in first line we posted output to browser but still we are getting that header_sent() is not giving output as buffer has not yet posted the output to browser. So we will get the output like this
No header sent , so you can use PHP to redirect
So to send the output to browser we must exhaust the output buffer capacity. Here it is 4096. So we will try to send some more output to browser to exceed the limit and then check the if condition to know the header status. Let us learn from this example.
<?Php
ob_start();
for($i=1; $i<=278; $i++){ // header is sent at 273
echo "plus2net.com - ";
}
$step1 = ob_get_length();
echo $step1;
echo "<br><br>";
if (!headers_sent()) {
// No header sent , so you can use PHP to redirect //
header("HTTP/1.1 301 Moved Permanently");
header ("Location: mynewpage1.html");
exit;
}else{
// Header already sent, so use JavaScript to redirect //
print "<script>";
print " self.location='mynewpage2.html';";
print "</script>";
}
?>
In the above code we have used ob_start() and ob_get_length() to know the data in buffer. You can adjust the for loop by increasing or decreasing the $i value. Higher number of loops mean more data will be posted to buffer. Try by increasing maximum value of $i and see where the headers_sent() became TRUE.