Cannot modify header information – headers already sent by (output started at …) is a very popular error returned by PHP. You would receive this error if you are trying to set the header of a page after the header has already been sent to the client. There are two main ways of getting around this error.
Here’s how it works: every file that you request from the Internet comes with a header. This tells the browser how to handle that specific file. For instance it could be a page that the browser will display or an executable that it will download. The header will contain information about what type of file this is.
PHP sends the header of the web pages to the client each time a page is requested. If you change that header after it was already sent, PHP will return the “Cannot modify header information” error. Most of the time you change the header by using the header() function, as in the example below:
This tells the browser that it should open the URL http://www.geekpedia.com (thus get the header from there.) However if you place this line in the code after you already displayed the content, the headers have already been sent to the client. That’s simply because even if you don’t set your own header, each time you display anything on a page, even a blank space, PHP will send the headers for you. If you make use of the header() function after any such blank space or any other content for that matter, you’ll be attempting to send a new header to the client, which is not possible.
The same applies for other functions that attempt to change the header, such as setcookie() which – because the cookie travelers in the header – needs to be placed before any output is sent to the page.
Solution #1 – no output before header(), setcookie() and other header setting functions
Thus, the first solution to the “Cannot modify header information” error is to make sure you are not outputting any content at all before the call to the header() function.
Solution #2 – ob_start()
The second method consists in calling the ob_start() at the very top of the PHP script like this:
This will turn output buffering on. With output buffering the entire PHP script will be processed before any output is sent to the client. Thus all the PHP script will be aware of all the header changes and it will not send any headers until every line has been processed.
ob_start() may appear to slow down the loading time on server intensive pages, because the client will not be presented with any fragment of the page until the page is fully processed.