submitted by scross99
The “Headers Already Sent” error is incredibly common, and I receive many many questions from all over about what it is and what caused it. So let’s clear all of this up once and for all.
The HTTP response generally consists of two parts, the headers and the content. The headers in a HTTP response indicate the nature of the response and how it should be handled. For instance, the response might specify a ‘Location’ header. This tells the browser to automatically redirect to the url specified in that header.
The other part of the HTTP response is the content, which I’m sure you’re familiar with. This must be sent after the headers, and once the content has begun being sent, no more headers can be sent. The content is the HTML code or whatever else that you generate in your script. When you call the echo() function you’re outputting content to the browser.
Ok, so what does this have to do with the “Headers Already Sent” error? Well, this error occurs, when you are attempting to send a HTTP header after the content has begun being sent. In a HTTP response this is strictly not allowed, since the client has already begun processing the content and so is no longer bothered with headers and will ignore any that are now sent.
As I said before the session_start() function sends headers to the client. The header() function also sends headers to the client (I imagine the name gives this away). The most common instances of the “Headers Already Sent” error involve the programmer using either of these functions after they have sent content to the browser.
The solution to this problem is simply making sure you send all your headers before you start sending the content. If there is the possibility that you need to send a header part way through generating the content then you can use the output buffering functions (ob_start, ob_end_clean, ob_end_flush) to stop the content from being sent until the end of the script. If you don’t know them, look them up in the PHP Manual. You could also simply perform all of the processing prior to generating the output. Either way, you can’t send any headers after the transfer of the content has begun.