UTF-8 all the way through
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 useutf8mb4
encoding if autf8mb4_*
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 styleIf 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:
- UTF-8 should be set in the HTTP header, such as
Content-Type: text/html; charset=utf-8
. You can achieve that either by settingdefault_charset
in php.ini (preferred), or manually usingheader()
function. - 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).
- When encoding the output using
json_encode()
, addJSON_UNESCAPED_UNICODE
as a second parameter.
Input:
- Browsers will submit data in the character set specified for the document, hence nothing particular has to be done on the input.
- In case you have doubts about request encoding (in case it could be tampered with), you may 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.
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.
Very strange behaviour with UTF-8
It's important that your entire code has the same charset to avoid issues where characters displays incorrectly.
Here's a little list of things that has to be set to a specific charset.
Headers
Setting the charset in both HTML and PHP headers to UTF-8
PHP (PHP headers has to be placed before any output: PHP echo, whitespace, HTML!):
header('Content-Type: text/html; charset=utf-8');
HTML (HTML-headers are placed within the
<head>
/</head>
tag):<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Connection
You also need to specify the charset in the connection itself.
PDO (specified in the object itself):
$handler = new PDO('mysql:host=localhost;dbname=database;charset=utf8', 'username', 'password');
MySQLi: (placed directly after creating the connection,
$mysqli
is the connection object)$mysqli->set_charset("utf8"); // OOP style
mysqli_set_charset($mysqli, "utf8"); // procedural styleMySQL (depricated): (placed directly after creating the connection)
mysql_set_charset("utf8");
Database
Your database and its tables has to be set to UTF-8. Note that charset is not the same as collation.
You can do that by running the queries below once for each database and tables (for example in phpMyAdmin)
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;Caution... There are various different situations that need different
ALTERs
. Details Here . Doing the wrongALTER
is likely to make things worse. -- Rick James
php.ini specification
In your
php.ini
file, you should specify the default charset for your platform, like thisdefault_charset = "utf-8";
(This is in essence the same as doing
header('Content-Type: text/html; charset=utf-8');
on all pages)
File-encoding
- It's also important that the
.php
file itself is UTF-8 encoded. If you're using Notepad++ to write your code, this can be done in the "Format" drop-down on the taskbar. You should use UTF-8 w/o BOM.
Should you follow all of the pointers above, chances are your problem will be solved. If not, you can take a look at this StackOverflow post: UTF-8 all the way through.
Changing encoding and charset to UTF-8
is UTF-8 backwards compatible with ISO-8859-1?
Unicode is a superset of the code points contained in ISO-8859-1 so all the "characters" can be represented in UTF-8 but how they map to byte values is different. There is overlap between the encoded values but it is not 100%.
In terms of serving content or processing forms submissions you are unlikely to have many issues.
It may mean a breaking change for URL handling. For example, for a parameter value naïve
there would be two incompatible forms:
http://example.com/foo?p=na%EFve
http://example.com/foo?p=na%C3%AFve
This is only likely to be an issue if there are external applications relying on the old form.
Related Topics
Using JavaScript History.Back() Fails in Safari .. How to Make It Cross-Browser
How to Have Dynamic Image as CSS Background
Removing Specific Elements from Json Encoded Array by Use of PHP
Curl (7): Failed to Connect to Localhost Port 8000: Connection Refused
Failed to Open the System Default Web Browser. Is One Installed - Pgadmin4
Regex: Number Range Excluding Specific Number
Php Fatal Error: Uncaught Pdoexception: Could Not Find Driver
How to Set Current Date as Default Value of an Input
Getting Error in Console:Failed to Load Resource: Net::Err_Connection_Reset
How to Get All Month Record Count in Laravel
How to Get Previous Month from Selected Month
Remove License Check from Script Code in Codeigniter
Checking Dates If Between Range of Dates in Laravel 5
Check If Class Property Is Not Null Before Calling Any Public Class Method
How to Save a Png Image Server-Side, from a Base64 Data Uri
MySQL Great Circle Distance (Haversine Formula)