UTF-8 all the way through

180,235

Solution 1

Data Storage:

  • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).

  • In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

Data Access:

  • In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

    • If you're using the PDO abstraction layer with PHP ≥ 5.3.6, you can specify charset in the DSN:

       $dbh = new PDO('mysql:charset=utf8mb4');
      
    • If you're using mysqli, you can call set_charset():

        $mysqli->set_charset('utf8mb4');       // object oriented style
        mysqli_set_charset($link, 'utf8mb4');  // procedural style
      
    • If you're stuck with plain mysql but happen to be running PHP ≥ 5.2.3, you can call mysql_set_charset.

  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

  • The same consideration regarding utf8mb4/utf8 applies as above.

Output:

  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).

  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.

  • When encoding the output using json_encode(), add JSON_UNESCAPED_UNICODE as a second parameter.

Input:

  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding() does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.

  • From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:

    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients "should" default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.

Other Code Considerations:

  • Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.

  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring extension.

  • PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.

  • To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

Solution 2

I'd like to add one thing to chazomaticus' excellent answer:

Don't forget the META tag either (like this, or the HTML4 or XHTML version of it):

<meta charset="utf-8">

That seems trivial, but IE7 has given me problems with that before.

I was doing everything right; the database, database connection and Content-Type HTTP header were all set to UTF-8, and it worked fine in all other browsers, but Internet Explorer still insisted on using the "Western European" encoding.

It turned out the page was missing the META tag. Adding that solved the problem.

Edit:

The W3C actually has a rather large section dedicated to I18N. They have a number of articles related to this issue – describing the HTTP, (X)HTML and CSS side of things:

They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).

Solution 3

In addition to setting default_charset in php.ini, you can send the correct charset using header() from within your code, before any output:

header('Content-Type: text/html; charset=utf-8');

Working with Unicode in PHP is easy as long as you realize that most of the string functions don't work with Unicode, and some might mangle strings completely. PHP considers "characters" to be 1 byte long. Sometimes this is okay (for example, explode() only looks for a byte sequence and uses it as a separator -- so it doesn't matter what actual characters you look for). But other times, when the function is actually designed to work on characters, PHP has no idea that your text has multi-byte characters that are found with Unicode.

A good library to check into is phputf8. This rewrites all of the "bad" functions so you can safely work on UTF8 strings. There are extensions like the mbstring extension that try to do this for you, too, but I prefer using the library because it's more portable (but I write mass-market products, so that's important for me). But phputf8 can use mbstring behind the scenes, anyway, to increase performance.

Solution 4

Warning: This answer applies to PHP 5.3.5 and lower. Do not use it for PHP version 5.3.6 (released in March 2011) or later.

Compare with Palec's answer to PDO + MySQL and broken UTF-8 encoding.


I found an issue with someone using PDO and the answer was to use this for the PDO connection string:

$pdo = new PDO(
    'mysql:host=mysql.example.com;dbname=example_db',
    "username",
    "password",
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

The site I took this from is down, but I was able to get it using the Google cache, luckily.

Solution 5

In my case, I was using mb_split, which uses regex. Therefore I also had to manually make sure the regex encoding was utf-8 by doing mb_regex_encoding('UTF-8');

As a side note, I also discovered by running mb_internal_encoding() that the internal encoding wasn't utf-8, and I changed that by running mb_internal_encoding("UTF-8");.

Share:
180,235
mercutio
Author by

mercutio

I'm a web applications developer from England. I specialize in PHP, although well versed in many other languages and technologies.

Updated on July 08, 2022

Comments

  • mercutio
    mercutio almost 2 years

    I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.

    Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?

    This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.

  • chazomaticus
    chazomaticus over 15 years
    I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
  • R. Martinho Fernandes
    R. Martinho Fernandes about 11 years
    Note that MySQL does not speak the same language as everyone else. When MySQL says "utf8" it really means "some weirdly retarded variant of UTF-8 that is limited to three bytes for god knows what ridiculous reason". If you really want UTF-8 you should tell MySQL that you want this weird thing MySQL likes to call utf8mb4. Don't bother saving on the "WTF!"s.
  • Simon East
    Simon East over 10 years
    Great tip about the func_overload setting - allows for minimal modification to existing code.
  • JW.
    JW. over 10 years
    Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
  • Alexander Yancharuk
    Alexander Yancharuk about 10 years
    Yes, right. Mysqli and PDO can use their native drivers. Also they can use mysqlnd driver if you will compile php with --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd options.
  • Marten Koetsier
    Marten Koetsier over 8 years
    Looking for this a bit further, this is only necessary for PHP versions prior to 5.3.6. See also: http://stackoverflow.com/a/4361485/2286722 (although they use a separate $dbh->exec("set names utf8");; I do prefer the method presented here). Btw. there is also a similar note on this as a comment in the PHP manual: php.net/manual/en/pdo.construct.php#96325.
  • Funk Forty Niner
    Funk Forty Niner over 7 years
    I spent an hour trying to figure out an encoding problem on a page I'm working on and I'm usually pretty good at figuring out stuff. I always consult this page and your answer helped me a lot. Got my upvote. In my case, set_charset('utf8mb4') did not work but >set_charset("utf8") did and that wasn't actually shown in the other answers.
  • Simba
    Simba about 7 years
    Important to note that the mbstring.func_overload feature is being deprecated as of PHP 7.2, due to the issues noted in @JW's comment above. So the best advice is: Yes you should definitely use the mbstring functions, but don't use the overload feature to get the standard functions to work as multibyte.
  • Martin Hennings
    Martin Hennings about 6 years
    @FunkFortyNiner Beware: set_charset("utf8") may work but will behave differently (see the remarks about the difference between utf8 and utf8mb4 and the mysql version history). Use utf8 if you have to AND ONLY if you know what you're doing!
  • Peter Mortensen
    Peter Mortensen almost 5 years
  • صلي علي محمد - Atef Farouk
    صلي علي محمد - Atef Farouk over 4 years
    5 stars solution, I was reading a text file line by line and getting ? for each character, then I did save-as , instead of ansi, used utf8. thanks.
  • dolmen
    dolmen about 2 years
    utf8mb4 is the charset to use.
  • dolmen
    dolmen about 2 years
    utf8mb4 is the charset to use for MySQL.
  • Dimitris Papageorgiou
    Dimitris Papageorgiou almost 2 years
    @chazomaticus do you think I should user mbstring even for English....or strlen will suffice? What about Greek?