Best Practices MySQL PHP

Authored by Corey Ballou


Setting up UTF-8 Encoding in PHP and MySQL

Use this as a quick reference for when you spin up a new machine and need to prepare yourself for site internationalization via proper UTF8 character encoding.

Switching to UTF-8 in MySQL

For starters, open up your my.cnf file, generally located in /etc/my.cnf or /etc/mysql/my.cnf, and add the following lines to the appropriate sections:

loose-default-character-set = utf8

loose-default-character-set = utf8

collation-server = utf8_unicode_ci
loose-default-character-set = utf8
character-set-server = utf8
init-connect = 'SET NAMES utf8'

Switching to UTF-8 in PHP

Open up your php.ini file, generally located in /etc/php.ini, /etc/php5/php.ini, or /etc/php5/apache2/php.ini, and add or replace the following line:

default_charset = "UTF-8"

Switching to UTF-8 in Apache

If you use the Apache web server, you’ll also want to set UTF-8 as the default charset there as well. Generally speaking, you want to add the following tag to your httpd.conf value, but sometimes the config option is already set in an include file such as /etc/apache2/conf.d/charset.

AddDefaultCharset UTF-8

Switching to UTF-8 in Nginx

If you use nginx as a webserver, simply add charset utf-8; inside of your server { } declaration.

One last thing…

Don’t forget to restart your web server and MySQL!

/etc/init.d/mysqld restart
/etc/init.d/apache2 restart # or.. apache2ctl graceful
/etc/init.d/nginx restart

Author: Corey Ballou

Corey Ballou is the CEO of Whether you're a student, young professional, entrepreneur, startup, or small business, you can be up and online fast with your own custom domain, email, and webpage on POP. Corey is a professional PHP developer by trade, specializing in custom web applications development for startups, small businesses, and agencies. Follow Corey on Twitter @cballou.

  • Jeff ‘SKI’ Kinsey

    Nice. Very much to the point.

  • em2008

    thanks much, too!

  • umar”debianista”zuki

    I had done all the above and still seing “” on Joomla site, please suggest where else to look.

    • Zach

      You need to dump the database with –default-character-set=latin1, remove SET NAMES from the dump file, go into MySQL CLI with –default-character-set=utf8, execute “SET names ‘utf8’;” in CLI, then “source /path/to/dump.sql;” (both of the previous commands without the double quotes.

      Your characters should then show up as expected.