Tag Archives: headers

Warning “headers already sent by” while developing PHP webapp

22 May

What are headers?

Every time you respond a request, there are some information attached at the beginning of the response. Those are headers. For example:

HTTP/1.1 200 OK
Date: Wed, 08 Feb 2006 08:20:07 GMT
Server: Apache/2.0.54 (Debian GNU/Linux) mod_auth_pgsql/2.0.2b1 mod_ssl/2.0.54 OpenSSL/0.9.7e
X-Powered-By: PHP/4.4.0
Transfer-Encoding: chunked
Content-Type: text/html

Those headers is used to control the browser behaviors such as caching, rendering… If you want to learn more about how to use them, you can see more helps and instructions from here:


Why do I get this warning?

Sometimes, you receive the warnings like this: “… headers already sent by”. It’s also mentioned in that article, but I will summarize the reason here. You got that warning because you call a function like header() or session_start() after sending page content. The page content includes what you sent to browser by echo, print, or whatever outside the server tag <? … ?>. Be caution: the headers must be sent before any other responses.

But actually I did not send any page content before calling header function? Why the warnings are still there?

This is one of the stupid bugs that PHP developers usually get. The page content includes ANY THINGS outside the server tags <? … ?>, that means white spaces and new line characters are also counted as well. Check your code again, maybe you left some blanks after the ending tag ?> in one of your included file.

Ah, one more thing! When you save your files as “UTF-8 with signature” on Windows platforms, 3 bytes with hex code “EFBBBF” will be inserted automatically at the beginning of the files. Those bytes are used to let Windows regconize that the file contains UTF-8 text. They’re unneeded in PHP because PHP won’t treat this signature. It considers those bytes as page content because they appear before the opening tag <?. As the result, any calling to header() and session_start() will be failed. If you’re using Zend Studio, choose the Encoding to “UTF-8 without signature” when saving.