PHP “headers already sent”, but I didn’t do it!

The Problem

I get the PHP Error:

PHP Warning:  Cannot modify header information - headers already sent by (output started at index.php:1) in /Path/...

when calling a PHP script! My scripts appear to be outputting data to the browser before any function to manage the buffer such as ob_flush() or ob_get_contents() is even being called! What is going on!?

The Details

The culprit may be a UTF-8 BOM (byte order mark) in a source file. The BOM is a sequence of bytes at the beginning of a file which tells whatever program is reading it how to correctly interpret the data contained in the file. For more information on BOM, see the links below.

This problem is particularly hard to catch because the BOM is output to the browser as non-printable characters, and won’t show up in the source. The BOM results in PHP not immediately recognizing the file as a PHP source file. This is a problem because PHP normally parses the first bytes of a script for the telltale “<?php”, but when a BOM is present it finds the BOM bytes instead. This causes PHP to not recognize the script as a PHP source file and consequently it begins to output to the browser (the output buffer is immediately flushed, as with calling ob_flush or its kin), effectively rendering any and all subsequent calls to modify buffered information (such as modifying headers, etc..) moot, and ending with the PHP Error: “Cannot modify header information – headers already sent”.

The Solution

When using UTF-8 don’t save your source files with a UTF-8 BOM!

You should check all included files which are accessed during the call, because a BOM in any of the files will cause this behavior!

It may also be useful to note that in the versions of PHP which I have tested (5.1.6 and 5.3.3) with a leading newline and/or blank line at the beginning of the file causes the same behavior (i.e. a newline before the opening “<?php” tag). However, any trailing spaces in the file do not appear to cause this behavior.

If you are still having other encoding related problems, there are various workarounds if you are using a source file which does in fact contain UTF-8 characters, for more info see the links below.

There is debate about whether this is a bug or not, but the bottom line is that the BOM confuses most versions of PHP, so it is not immediately clear whether this “bug” will be fixed or not.

More Info at:

https://bugs.php.net/bug.php?id=22108
http://www.w3.org/International/questions/qa-utf8-bom.en.php
http://en.wikipedia.org/wiki/Byte_order_mark
http://stackoverflow.com/questions/2558172/utf-8-bom-signature-in-php-files


Read more of my posts on my blog at http://blog.tinned-software.net/.

This entry was posted in PHP and tagged , , , . Bookmark the permalink.