Posts Tagged ‘location’

Headers already sent error php solution

Sunday, June 22nd, 2008

Many people seem to get a problem with the common error message of

Warning: Cannot modify header information - headers already sent by (output started at C:\file.php:1) in C:\file.php on line 4)

There are a number of possible reasons for why this might happen

Output before the <?php tag

There are so many occasions where people report that they have no output, only to find that they have a single space or a new line before their opening <?php tag. Examples

 

appears to be fine to the untrained eye, but upon further inspection we notice that their is a slight gap (one space) before the <?php tag.


also looks fine, however a single carriage return still gets output to the browser, so it's still going to cause the same problem

Output inside your script via functions

php has a number of functions that display code, such as echo(), var_dump() and print_r(). Some people also believe that (X)HTML code does not qualify as content for some reason, and leave it there. This is STILL output, and will still bring up the error. Another instance where people get confused is where there is more than one error on the page. For instance if a Notice: error message comes up before the headers are sent, this will also be classed as an output, therefore turn off notice messages (This should be the case anyway for production servers)

The error is caused by a different file

Warning: Cannot modify header information - headers already sent by (output started at /home/username/www/includedfile.php:1) in /home/username/www/file.php on line 4)
Above shows the location of the file where the output was started at, and also, the line on which it started. Simply go to that line with your editor in that file, and work out what is causing the output. This type of error is common when using include/include_once or require/require_once

When including php from other files, it is a good idea to not have the closing ?> tag. This will NOT affect your script in any way, as PHP is quite happy with no tag. It will also prevent output being left after the tag such as the single space/new line as mentioned above. This is good practice and I recommend doing this with any included files with php, since you should not mix both (X)HTML and PHP in includes other than templates