PHP: Avoiding “Headers already sent by…” errors

March 3rd, 2008 by Richy B. Leave a reply »

Just a quick post inspired by Techgirl, here’s how to avoid the annoying PHP errors “Headers already sent by…” when working with multiple files.

Basically, a PHP script usually looks like:

<?php
include "my.lib.php";
include "otherstuff.php";
....
?>

however, if my.lib.php (for example) looks like:

<?php
....
...
?>


(do you see the hidden “new line at the end”), you’ll get the “Warning: Cannot modify header information – headers already sent by (output started at my.lib.php:6) in index.php on line 2? error.

So how do you simpley avoid this? Easy! Omit the closing ?> from the library/include files. My.lib.php now looks like:

<?php
....
...

and the problem is solved.

Simple, quick solution which is worth remembering!

This post is over 6 months old.

This means that, despite my best intentions, it may no longer be accurate.

This blog holds over 12 years of archived content - during that time, I may have changed my opinion of something, technology will have advanced (and old "best standards" may no longer be the case), my technology "know how" has improved etc etc - it would probably take me a considerable amount of time to update all the archival entries: and defeat the point of keeping them anyway.

Please take these posts for what they are: a brief look into my past, my history, my journey and "caveat emptor".

Leave a Reply

gamy-dance
%d bloggers like this: