Philip Ronan <in*****@invalid.invalid> wrote:
Q. Why am I getting the error message 'Headers already sent'?
[ A. the explanation why and how to counter the symptoms]
If you get this error your script flow is broken (in most cases). Using
OB is nothing more than hiding the symptoms of the error.
The error tells you where the real problem lies:
1:<?php
2:error_reporting(E_ALL);
3://do stuff
4:echo "redirecting";
5:
6://do more stuff
7:
8:header("Location: http://localhost/");
9:?>
will produce the error:
Warning: Cannot modify header information - headers already sent by
(output started at /path/to/script.php:4) in /path/to/script.php on line 8
What is really is trying to say:
Error: line 8 at /path/to/script.php can't send headers. The problem is
at line 4 in /path/to/script.php, it produced some output to the client
so I already had sent all headers before getting to line 8.
But since you already have all required userinput you should find out
wheter you need to sent additional headers (like a redirect) before
outputting anything to the client. So the equivalent script with correct
top down flow would be:
1:<?php
2:error_reporting(E_ALL);
3:if($condition){
4:header("Location: http://localhost/");
5:die("redirecting");
6:}
7:
8:echo "condition was false";
9:?>
The following script:
1:<?php
2://do stuff
3:?>
4:<html><body>
5:Redirecting
6:</body></html>
7:<?php
8:header("Location: http://tmp.tryba.nl/");
9:?>
Produces:
Warning: Cannot modify header information - headers already sent by
(output started at /path/to/script.php:7) in /path/to/script.php on line 8
Now it complains about line 7 since the <?php line 7 apparently flushed
the stringbuffer that got build between lines 3 and 7.
When including file the error could look like this:
Warning: Cannot modify header information - headers already sent by
(output started at /path/to/other.php:5) in /path/to/script.php on line 6
Now it is other.php which produces output to the browser at line 5, so
line 6 in script.php can't modify headers any longer.