The PHP "headers already sent" error message

Still in my early days working with PHP, I've learned that it's really easy to generate the dreaded "headers already sent" error message. If for some reason you actually want to generate this error message intentionally, I've learned that all you have to do is try to send HTML body content (any non-header content) before calling the header() or setcookie() methods, and you'll get that PHP error message right away.

Since you really don't ever want to see the "headers already sent" error message, let me re-phrase that paragraph: You get this error message when you send body content to the browser before sending your header content with the header() or setcookie() methods. So, to fix this problem, review your PHP code to determine how/where the body content is being sent before the header content, and then fix the problem.

A simple demonstration of the problem

As a really simple example of the problem, the following PHP code will intentionally generate the "headers already sent" error message:

// intentionally generate the "headers already sent" error
// by sending body content before calling setcookie().
// (don't do this)
print "The body ...";
setcookie('favorite-cookie','chocolate chip');

To fix this problem, just reverse those calls, making sure the header content is sent to the browser first, like this:

// the corrected code
setcookie('favorite-cookie','chocolate chip');
print "The body ...";