Fix Strange “Headers already sent by” in Line 1 PHP File

“Cannot modify header information – headers already sent by” error is the most common PHP error that happens when we develop a web application, usually when we want to redirect or send a cookie. I used to get that warning a lot long ago. But since I standardized my PHP code, it hasn’t happened for a while now, until last night.

Yesterday night I was fixing somebody else’s code and auditing the performance as well as the security. But when testing it, I got a very strange error: “Headers already sent by” at line 1. I opened the file and saw that at line 1, there was nothing there — just a PHP open tag, and nothing else.

It confused me for an hour until I finally got the answer from this StackOverflow thread. The problem is there is an invisible whitespace character before the open PHP tag. To check it I used Notepad++ with a plugin called Hex Editor. And I found there was an invisible character at the beginning of the file.

I cleaned it, checked every file and voila, everything works like a charm. So if you encounter any strange errors and come to this article, it is worth checking it out.