NEVER EVER SAVE PHP IN UTF-8 WITH BOM

Just another quick debug task.
That client’s vendor said they spent many hours but still no idea why.

Well, I spent more time on writing this post than actual debugging.

Symptom:

AJAX Login form broken after recent program update, JSON result seems returned normally but jQuery failed to parse it.

Firebug reports a strange error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Screenshot from 2014-08-09 03:17:17

What’s in line 1 column 1? It’s character “{“… But why is the “{” unexpected?
It looks perfectly legit…

Copied the JSON to JSONLint and it reported the exactly same error.
But error goes away magically after I delete thay “{” and typed it again.

Hmm… it looks familiar.

Cause & Fix:

Many years ago when I am a PHP n00b, after I just save every BIG5 file into UTF-8.
Website broke with “Header already sent” PHP errors and AJAX calls reported strange errors.

Copy the text into Notepad++ and open it in WinHex, you will see there are three strange bytes in the beginning: 0xEF,0xBB,0xBF

Yes, it’s the UTF-8 BOM. The error must be caused by some files accidentally saved in UTF-8 with BOM.

Just find where the file is…

grep -rl --include '*.php' $'\xEF\xBB\xBF' .

Re-saved the file without BOM, bug fixed!

Conclusion:

Silly mistake.

NEVER EVER SAVE PHP IN UTF-8 WITH BOM

And be careful when using Notepad to edit PHP file (Which saves in ASCII and UTF-8 WITH BOM by default)

There have been many wasted hours around the Internet on this issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.