I encountered a frustrating problem regarding HTTP content type headers today. It massively broke the design of my site in Firefox, but didn’t seem to affect anything in Internet Explorer. The lesson learned is to be very careful where you send the Content-Type header using PHP.
I’ve been working on a new website which divides the CSS into two separate files: one which governs layout, and one which governs aesthetic styles like colours and fonts. In both IE and FF, the layout itself was fine. But in FF the aesthetic stylesheet wasn’t having any effect at all. It’s as though it wasn’t being included. I checked absolutely everything I could think of, but to no avail.
Finally, I spotted the problem. The aesthetic stylesheet was actually a PHP script, because we wanted to be able to swap-out colour schemes dynamically during development for testing different ideas. As such, I was careful to tell PHP to push a suitable Content-Type header at the top of the file, before anything was output:
header("Content-Type: text/css; charset=utf-8");
If you don’t do that then the CSS file usually gets sent as “text/html”, which confuses some browsers.
Immediately after that header command, I was including our site’s general “config” script so we could grab current colour scheme details. Unfortunately, I had unthinkingly put a generic Content-Type header command in there for convenience, as it’s included on all our regular HTML pages. Naturally, it was a “text/html” type.
Lo and behold, Firefox saw the second Content-Type header as being the correct one, and therefore ignored that CSS script. Evidently IE doesn’t really care about accurate content types, which is why it seemed to work there. So always remember to handle HTTP headers with care!