From what I have studied, headers cannot be changed after there is an output from a script. Why is it then that in this code sample that I wrote, the script has several outputs before it creates a new header, and yet everything works fine?
<?php
$name = "tommy" ;
?>
<?php
headers_sent($filename, $linenum) ;
header("name: $name") ;
echo "tommy <br>" ;
echo "Headers sent in $filename on line $linenum" ;
?>
In addition the output says that the headers were sent in line 0... how is that possible if I added a header afterwards?
The first thing you need to do when you run into the “Cannot modify header information – headers already sent by” error is to open the file that's causing the problem. Then, locate the line the message indicates. In this scenario, you can reach the source of the problem using the WordPress theme editor.
What Does “Cannot Modify Header Information – Headers Already Sent By” Mean? The “Cannot Modify Header Information – Headers Already Sent By” error indicates that a . php file cannot execute because an output is being sent before calling an HTTP header. Headers always need to precede the output.
headers_sent() function checking whether header has already been sent or not. so ! headers_sent() returns false for which header are not being sent again, avoiding the errors.
PHP has to pass the headers to the webserver first. It can only do that once. After the double linebreak it can nevermore amend them. When PHP receives the first output ( print , echo , <html> ) it will flush all collected headers. Afterward it can send all the output it wants.
Check if you have Output Buffering set to On in your php.ini. It might also be On by default on some PHP versions, according to this comment on php.net: http://www.php.net/manual/en/ref.outcontrol.php#69059
If that's the case, that's probably why your script executes fine with no errors, even though there is "output" before headers are sent.
EDIT: If you don't have access to the php.ini file itself, you can probably check the value of output buffering from your PHP script by calling ini_get('output_buffering');
.
Output means, in this case, sending information to the client. Could be an echo
, print_r
or another form of outputting info in the screen.
There are more ways of outputting data, for example: setting a cookie will also send output. You can't set a cookie and proceed with header changes.
The error in your code:
On line 3 you close php ?>
and open it on line 5 <?php
. Line 4 is output, a \n
(newline-character). This will throw an error.
If you do not see that error, your error levels are probaly wrong. You can do an echo above your header, if you still get no errors, it's error_reporting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With