PHP and UTF-8 Woes

Do you find yourself working with foreign characters and they go all screwy when you use forms or your MySQL database? You could have UTF-8 issues. If you are unsure what UTF-8 is and why it is important, here’s a great resource http://utf8everywhere.org/ where you can find out more, but let’s assume you know your  characters but need a solution for working with them using PHP, MySQL and forms. Firstly, have you ensured your pdo database connection is using UTF-8 because that is the most likely cause (assuming you are using that, right? If not, please adapt):

new PDO('mysql:host=HOSTNAME;dbname=DBNAME,
USERNAME,
PASSWORD,
array(PDO::MYSQL\_ATTR\_INIT_COMMAND => "SET NAMES 'utf8'")
);

The important parts are the options with the array. That’s one solution if you are using PHP < 5.3.6 but newer than that, this is preferable:

new PDO('mysql:host=HOSTNAME;dbname=DBNAME;charset=utf8',
USERNAME,
PASSWORD)
);

Here, the difference is the charset part. That should have fixed it but if not, here are a couple of other things you really ought to be doing anyway. Find your PHP.ini file and ensure that the following line is set:

default_charset="UTF-8"

One last thing coming up! In all your HTML files, ensure you have the following in your head section:

1
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Happy charactering :-)


Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com