Warning: Cannot modify header information – headers already sent by …
Aghrrr, huh?
Have you ever faced this ugly message? I can bet your answer is "Yes!" and even "Yes, a lot!"
Ok, I would say the second answer: Yes, a lot.
If you have a bit experience you should know that due the RFC the headers are ALWAYS sent before any other output to the browser.
Headers are pieces of information sent to the browser that aren't displayed, like the type of content, the charset to be used, the expiration of the content, even cookies are sent as headers.
So this is fine:
-
<?php
-
// Hello
-
// World
-
?>
-
-
<html>
-
<body>
-
Hi there!
-
</body>
-
</html>
But, what about this:
-
<?php
-
// Hello
-
?>
-
-
<?php
-
// World
-
?>
-
-
<html>
-
<body>
-
Hi there!
-
</body>
-
</html>
"Warning: Cannot modify header information - headers already sent by (output started at /.../tests/headers_sent.php:5) in /.../tests/headers_sent.php on line 8 Hi there!"
Hey, what's wrong with it?
Well, if you look closer you'll note there's a space between the PHP blocks:
-
<?php
-
// Hello
-
?>
-
-
<?php
-
// World
-
?>
You would say: It's fine, I've just pressed ENTER on my keyboard.. no spaces, anything to print. I'm neat and I like to split code in blocks. What's up?
Ok, this is what happens: that line is there because of a line break, a "rn" so that you see it there, and the browser will see it too.
If the browser sees any content before a header (or put it like this: a header arrives after the "content" started to come) you're violating the rules.
What the ugly message "headers already sent" means is "hey, the contents started to come, I'm not expecting more headers to be sent - time up for them".
Even without a space in the blank line between blocks happened to give the same error (I can't reproduce it again in my PHP Version -5.3.1-, but I faced it before, I guess in 5.2.x).
So the solution for this is to remove any space or line break before ending all your php logic at the top of the script.
My advice is: Do not split your logic in PHP blocks, instead use a whole code block but put comments in it; something like this:
-
<?php
-
// Code Block - Step #1
-
//-------------------------
-
Your stuff...
-
-
// Code Block - Step #2
-
//-------------------------
-
Yada yada yada...
-
?>
Another solution is to enable the output buffering, but I'll talk about it in another post.
I hope this tip helps somebody. :)
PS: More on headers here
.: Pampa :.
