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):
- Having previously in the script (or including a file which have it) whitespaces :
- 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:
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: