Warning: Cannot modify header information – headers already sent

Sometimes programming with PHP and trying to redirect pages with header(“location:”.$site); , it’s possible to get the following warning:
Warning: Cannot modify header information – headers already sent
This may occur for one of those reasons:

  • Start the file with (or including a file which starts with):
    1
    2
    3
    
    <?php
     
    // the code starts here, above there's a whitespace
  • Having previously in the script (or including a file which have it) whitespaces :
    1
    2
    3
    4
    5
    6
    7
    
    <?php
    // some example code...
    ?>
     
    <?php
    // more example code lines...
    ?>
  • Print or echo of a variable or text before sending headers.
  • HTML code before sending headers.
  • A mix of the above reasons…

Sometimes, depending on PHP version, everything seems to be okay but when you run the script, it doesn’t work. Let’s see an example:

Warning: Cannot modify header information – headers already sent by (output started at /full/route/to/file/which/previously/has/sent/headers/included.php:xx) in /full/route/which/has/sending/header/script.php on line xx

In script.php there is eg. header(“location:script2.php); and apparently headers has sent before in included.php.

In included.php:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
// code
if ($lang== "es")
{
	include("spanish.inc.php");
}
elseif ($lang== "en")
{
	include("english.inc.php");
}
// more code
?>

Imagine your error is on include(“spanish.inc.php”) and obviously the included file is ok (eg. empty). Then why there’s an error? Some php versions or apache/iis configurations, make an include (or require, require_once, …) works as an output buffer. To avoid that, just wrap the “conflictive” code with:

ob_start();
// code which have include or require, etc.
ob_clean();

So, finally In included.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// code
ob_start();
if ($lang== "es")
{
	include("spanish.inc.php");
}
elseif ($lang== "en")
{
	include("english.inc.php");
}
ob_clean();
// more code
?>

 

More information about those php functions here and here.

Leave a Reply

Your email address will not be published. Required fields are marked *