UTF-8 all the way through
up vote
1041
down vote
favorite
I'm setting up a new server, and want to support UTF-8 fully in my web application. I have tried 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.
php mysql linux apache utf-8
add a comment |
up vote
1041
down vote
favorite
I'm setting up a new server, and want to support UTF-8 fully in my web application. I have tried 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.
php mysql linux apache utf-8
8
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
12
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
This problem is common. But there is no shortcut solution, you will have to setuputf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.
– Manish Shrivastava
Jan 18 '17 at 14:00
add a comment |
up vote
1041
down vote
favorite
up vote
1041
down vote
favorite
I'm setting up a new server, and want to support UTF-8 fully in my web application. I have tried 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.
php mysql linux apache utf-8
I'm setting up a new server, and want to support UTF-8 fully in my web application. I have tried 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.
php mysql linux apache utf-8
php mysql linux apache utf-8
edited Jan 9 at 15:49
Machavity
24.1k135478
24.1k135478
asked Nov 10 '08 at 21:04
mercutio
11.9k93136
11.9k93136
8
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
12
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
This problem is common. But there is no shortcut solution, you will have to setuputf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.
– Manish Shrivastava
Jan 18 '17 at 14:00
add a comment |
8
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
12
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
This problem is common. But there is no shortcut solution, you will have to setuputf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.
– Manish Shrivastava
Jan 18 '17 at 14:00
8
8
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
12
12
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
This problem is common. But there is no shortcut solution, you will have to setup
utf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.– Manish Shrivastava
Jan 18 '17 at 14:00
This problem is common. But there is no shortcut solution, you will have to setup
utf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.– Manish Shrivastava
Jan 18 '17 at 14:00
add a comment |
13 Answers
13
active
oldest
votes
up vote
899
down vote
accepted
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 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 theContent-Type
MIME header yourself, which is just more work but has the same effect.
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 the only way to reliably do this is add theaccept-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.
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
|
show 11 more comments
up vote
138
down vote
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:
- FAQ: Changing (X)HTML page encoding to UTF-8
- Declaring character encodings in HTML
- Tutorial: Character sets & encodings in XHTML, HTML and CSS
- Setting the HTTP charset parameter
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
add a comment |
up vote
56
down vote
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.
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
add a comment |
up vote
26
down vote
Old topic, I know. 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, was able to get it using google cache luckily.
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.
– Marten Koetsier
Aug 13 '15 at 13:55
add a comment |
up vote
20
down vote
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");
.
add a comment |
up vote
19
down vote
First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.
I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.
I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14
INTL
Good:
- Wrapper around ICU library
- Standardised locales, set locale per script
- Number formatting
- Currency formatting
- Message formatting (replaces gettext)
- Calendars, dates, timezone and time
- Transliterator
- Spoofchecker
- Resource bundles
- Convertors
- IDN support
- Graphemes
- Collation
- Iterators
Bad:
- Does not support zend_multibite
- Does not support HTTP input output conversion
- Does not support function overloading
mb_string
- Enables zend_multibyte support
- Supports transparent HTTP in/out encoding
- Provides some wrappers for funtionallity such as strtoupper
ICONV
- Primary for charset conversion
- Output buffer handler
- mime encoding functionality
- conversion
- some string helpers (len, substr, strpos, strrpos)
- Stream Filter
stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')
DATABASES
- mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
- postgresql: pg_set_client_encoding
- sqlite(3): Make sure it was compiled with unicode and intl support
Some other Gotchas
- You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
- Send everything in ASCII if you are using exec, proc_open and other command line calls
- Plain text is not plain text, files have encodings
- You can convert files on the fly with the iconv filter
I ll update this answer in case things change features added and so on.
2
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.
– Alexander Yancharuk
Feb 16 '14 at 17:54
add a comment |
up vote
13
down vote
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
add a comment |
up vote
12
down vote
The only thing I would add to these amazing answers is to emphasize on saving your files in utf8 encoding, i have noticed that browsers accept this property over setting utf8 as your code encoding. Any decent text editor will show you this, for example Notepad++ has a menu option for file enconding, it shows you the current encoding and enables you to change it. For all my php files I use utf8 without BOM.
Sometime ago i had someone ask me to add utf8 support for a php/mysql application designed by someone else, i noticed that all files were encoded in ANSI, so I had to use ICONV to convert all files, change the database tables to use the utf8 charset and utf8_general_ci collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier otherwise you have to use charset=utf8 in the connection string) and change string functions to use the php multibyte string functions equivalent.
add a comment |
up vote
8
down vote
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
add a comment |
up vote
8
down vote
I have just went through the same issue and found a good solution at PHP manuals.
I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %sn", $mysqli->error);
} else {
printf("Current character set: %sn", $mysqli->character_set_name());
}
View Source
2
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.
– Funk Forty Niner
Jan 21 '17 at 14:16
@FunkFortyNiner Beware:set_charset("utf8")
may work but will behave differently (see the remarks about the difference betweenutf8
andutf8mb4
and the mysql version history). Useutf8
if you have to AND ONLY if you know what you're doing!
– Martin Hennings
Apr 24 at 10:09
add a comment |
up vote
6
down vote
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
add a comment |
up vote
5
down vote
The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:
// storage
// debian. apparently already utf-8
// retrieval
// the mysql database was stored in utf-8,
// but apparently php was requesting iso. this worked:
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');
// delivery
// php.ini did not have a default charset,
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');
// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.
// processing
// changed a few commands in php, like substr,
// to mb_substr
that was all !
add a comment |
up vote
5
down vote
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
add a comment |
protected by hjpotter92 Jan 6 '14 at 12:57
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
13 Answers
13
active
oldest
votes
13 Answers
13
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
899
down vote
accepted
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 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 theContent-Type
MIME header yourself, which is just more work but has the same effect.
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 the only way to reliably do this is add theaccept-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.
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
|
show 11 more comments
up vote
899
down vote
accepted
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 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 theContent-Type
MIME header yourself, which is just more work but has the same effect.
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 the only way to reliably do this is add theaccept-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.
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
|
show 11 more comments
up vote
899
down vote
accepted
up vote
899
down vote
accepted
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 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 theContent-Type
MIME header yourself, which is just more work but has the same effect.
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 the only way to reliably do this is add theaccept-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.
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 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 theContent-Type
MIME header yourself, which is just more work but has the same effect.
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 the only way to reliably do this is add theaccept-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.
edited May 23 '17 at 12:34
Community♦
11
11
answered Nov 10 '08 at 21:43
chazomaticus
11.7k42530
11.7k42530
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
|
show 11 more comments
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
4
4
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
It's my understanding that if you specify the collation as utf8_*, it automatically encodes as utf8 as well. Is this wrong?
– chazomaticus
Nov 10 '08 at 21:49
47
47
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
I'm not wrong: COLLATE implies CHARACTER SET. See e.g. dev.mysql.com/doc/refman/5.0/en/charset-database.html.
– chazomaticus
Nov 10 '08 at 23:01
6
6
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
Consider adding PDO examples for setting the character set as well.
– Ja͢ck
Oct 22 '12 at 3:35
86
86
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
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.
– R. Martinho Fernandes
Apr 9 '13 at 9:21
4
4
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
This answer helped me so much BUT I also found that in my case I needed to add JSON_UNESCAPED_UNICODE to my PHP json_encode when passing the DB query results back via ajax.
– Petay87
Dec 14 '17 at 9:49
|
show 11 more comments
up vote
138
down vote
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:
- FAQ: Changing (X)HTML page encoding to UTF-8
- Declaring character encodings in HTML
- Tutorial: Character sets & encodings in XHTML, HTML and CSS
- Setting the HTTP charset parameter
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
add a comment |
up vote
138
down vote
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:
- FAQ: Changing (X)HTML page encoding to UTF-8
- Declaring character encodings in HTML
- Tutorial: Character sets & encodings in XHTML, HTML and CSS
- Setting the HTTP charset parameter
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
add a comment |
up vote
138
down vote
up vote
138
down vote
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:
- FAQ: Changing (X)HTML page encoding to UTF-8
- Declaring character encodings in HTML
- Tutorial: Character sets & encodings in XHTML, HTML and CSS
- Setting the HTTP charset parameter
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
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:
- FAQ: Changing (X)HTML page encoding to UTF-8
- Declaring character encodings in HTML
- Tutorial: Character sets & encodings in XHTML, HTML and CSS
- Setting the HTTP charset parameter
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
edited May 23 '17 at 12:02
Community♦
11
11
answered Nov 12 '08 at 19:27
mercator
24.5k85570
24.5k85570
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
add a comment |
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
Shouldn't it also be possible to specify the charset in the HTTP headers? Probably needs some config option for the webserver...
– oliver
Nov 20 '08 at 17:47
2
2
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
@oliver: Yes you can send it in the HTTP header, but it's better to send it in the content because if the client saves the file, it'll always save the meta tag. A HTTP header is likely to just disappear unless the browser is smart enough to copy it into a meta tag in the saved file.
– user42092
Dec 2 '08 at 1:49
5
5
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
Also, make sure that line is the first child of head element (before any Unicode stuff). The browser may reinterpret the page after hitting that meta element described above.
– alex
Apr 20 '10 at 8:55
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, hi dude, I am beginner in web development and faced the same issue, while trying to change language of formated date time I faced this issue 10 �������� 2018, I am using utf-8 in an html and I was suggested to make database and browser compatible with utf-8 so I can solve my problem. Please can you help me. I hope for your attention
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
@mercator, I am using PHP Laravel
– Mirich
Sep 10 at 12:48
add a comment |
up vote
56
down vote
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.
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
add a comment |
up vote
56
down vote
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.
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
add a comment |
up vote
56
down vote
up vote
56
down vote
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.
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.
edited Nov 10 '08 at 21:35
answered Nov 10 '08 at 21:30
chroder
3,28712139
3,28712139
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
add a comment |
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
Set the overload setting in the php.ini. It helps when using multi-byte strings.
– Anthony Rutledge
Dec 21 '15 at 20:52
add a comment |
up vote
26
down vote
Old topic, I know. 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, was able to get it using google cache luckily.
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.
– Marten Koetsier
Aug 13 '15 at 13:55
add a comment |
up vote
26
down vote
Old topic, I know. 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, was able to get it using google cache luckily.
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.
– Marten Koetsier
Aug 13 '15 at 13:55
add a comment |
up vote
26
down vote
up vote
26
down vote
Old topic, I know. 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, was able to get it using google cache luckily.
Old topic, I know. 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, was able to get it using google cache luckily.
edited Jan 26 '14 at 19:02
iankit
4,45573751
4,45573751
answered Sep 11 '12 at 15:40
Brad F Jacobs
16.4k44160
16.4k44160
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.
– Marten Koetsier
Aug 13 '15 at 13:55
add a comment |
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.
– Marten Koetsier
Aug 13 '15 at 13:55
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.– Marten Koetsier
Aug 13 '15 at 13:55
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.– Marten Koetsier
Aug 13 '15 at 13:55
add a comment |
up vote
20
down vote
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");
.
add a comment |
up vote
20
down vote
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");
.
add a comment |
up vote
20
down vote
up vote
20
down vote
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");
.
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");
.
answered Feb 23 '12 at 22:20
JDelage
4,6632063104
4,6632063104
add a comment |
add a comment |
up vote
19
down vote
First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.
I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.
I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14
INTL
Good:
- Wrapper around ICU library
- Standardised locales, set locale per script
- Number formatting
- Currency formatting
- Message formatting (replaces gettext)
- Calendars, dates, timezone and time
- Transliterator
- Spoofchecker
- Resource bundles
- Convertors
- IDN support
- Graphemes
- Collation
- Iterators
Bad:
- Does not support zend_multibite
- Does not support HTTP input output conversion
- Does not support function overloading
mb_string
- Enables zend_multibyte support
- Supports transparent HTTP in/out encoding
- Provides some wrappers for funtionallity such as strtoupper
ICONV
- Primary for charset conversion
- Output buffer handler
- mime encoding functionality
- conversion
- some string helpers (len, substr, strpos, strrpos)
- Stream Filter
stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')
DATABASES
- mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
- postgresql: pg_set_client_encoding
- sqlite(3): Make sure it was compiled with unicode and intl support
Some other Gotchas
- You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
- Send everything in ASCII if you are using exec, proc_open and other command line calls
- Plain text is not plain text, files have encodings
- You can convert files on the fly with the iconv filter
I ll update this answer in case things change features added and so on.
2
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.
– Alexander Yancharuk
Feb 16 '14 at 17:54
add a comment |
up vote
19
down vote
First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.
I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.
I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14
INTL
Good:
- Wrapper around ICU library
- Standardised locales, set locale per script
- Number formatting
- Currency formatting
- Message formatting (replaces gettext)
- Calendars, dates, timezone and time
- Transliterator
- Spoofchecker
- Resource bundles
- Convertors
- IDN support
- Graphemes
- Collation
- Iterators
Bad:
- Does not support zend_multibite
- Does not support HTTP input output conversion
- Does not support function overloading
mb_string
- Enables zend_multibyte support
- Supports transparent HTTP in/out encoding
- Provides some wrappers for funtionallity such as strtoupper
ICONV
- Primary for charset conversion
- Output buffer handler
- mime encoding functionality
- conversion
- some string helpers (len, substr, strpos, strrpos)
- Stream Filter
stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')
DATABASES
- mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
- postgresql: pg_set_client_encoding
- sqlite(3): Make sure it was compiled with unicode and intl support
Some other Gotchas
- You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
- Send everything in ASCII if you are using exec, proc_open and other command line calls
- Plain text is not plain text, files have encodings
- You can convert files on the fly with the iconv filter
I ll update this answer in case things change features added and so on.
2
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.
– Alexander Yancharuk
Feb 16 '14 at 17:54
add a comment |
up vote
19
down vote
up vote
19
down vote
First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.
I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.
I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14
INTL
Good:
- Wrapper around ICU library
- Standardised locales, set locale per script
- Number formatting
- Currency formatting
- Message formatting (replaces gettext)
- Calendars, dates, timezone and time
- Transliterator
- Spoofchecker
- Resource bundles
- Convertors
- IDN support
- Graphemes
- Collation
- Iterators
Bad:
- Does not support zend_multibite
- Does not support HTTP input output conversion
- Does not support function overloading
mb_string
- Enables zend_multibyte support
- Supports transparent HTTP in/out encoding
- Provides some wrappers for funtionallity such as strtoupper
ICONV
- Primary for charset conversion
- Output buffer handler
- mime encoding functionality
- conversion
- some string helpers (len, substr, strpos, strrpos)
- Stream Filter
stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')
DATABASES
- mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
- postgresql: pg_set_client_encoding
- sqlite(3): Make sure it was compiled with unicode and intl support
Some other Gotchas
- You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
- Send everything in ASCII if you are using exec, proc_open and other command line calls
- Plain text is not plain text, files have encodings
- You can convert files on the fly with the iconv filter
I ll update this answer in case things change features added and so on.
First of all if you are in < 5.3PHP then no. You've got a ton of problems to tackle.
I am surprised that none has mentioned the intl library, the one that has good support for unicode, graphemes, string operations , localisation and many more, see below.
I will quote some information about unicode support in PHP by Elizabeth Smith's slides at PHPBenelux'14
INTL
Good:
- Wrapper around ICU library
- Standardised locales, set locale per script
- Number formatting
- Currency formatting
- Message formatting (replaces gettext)
- Calendars, dates, timezone and time
- Transliterator
- Spoofchecker
- Resource bundles
- Convertors
- IDN support
- Graphemes
- Collation
- Iterators
Bad:
- Does not support zend_multibite
- Does not support HTTP input output conversion
- Does not support function overloading
mb_string
- Enables zend_multibyte support
- Supports transparent HTTP in/out encoding
- Provides some wrappers for funtionallity such as strtoupper
ICONV
- Primary for charset conversion
- Output buffer handler
- mime encoding functionality
- conversion
- some string helpers (len, substr, strpos, strrpos)
- Stream Filter
stream_filter_append($fp, 'convert.iconv.ISO-2022-JP/EUC-JP')
DATABASES
- mysql: Charset and collation on tables and on connection (not the collation). Also don't use mysql - msqli or PDO
- postgresql: pg_set_client_encoding
- sqlite(3): Make sure it was compiled with unicode and intl support
Some other Gotchas
- You cannot use unicode filenames with PHP and windows unless you use a 3rd part extension.
- Send everything in ASCII if you are using exec, proc_open and other command line calls
- Plain text is not plain text, files have encodings
- You can convert files on the fly with the iconv filter
I ll update this answer in case things change features added and so on.
edited Feb 16 '14 at 17:37
answered Jan 27 '14 at 9:16
Jimmy Kane
9,72465281
9,72465281
2
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.
– Alexander Yancharuk
Feb 16 '14 at 17:54
add a comment |
2
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.
– Alexander Yancharuk
Feb 16 '14 at 17:54
2
2
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.– Alexander Yancharuk
Feb 16 '14 at 17:54
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.– Alexander Yancharuk
Feb 16 '14 at 17:54
add a comment |
up vote
13
down vote
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
add a comment |
up vote
13
down vote
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
add a comment |
up vote
13
down vote
up vote
13
down vote
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
I recently discovered that using strtolower()
can cause issues where the data is truncated after a special character.
The solution was to use
mb_strtolower($string, 'UTF-8');
mb_ uses MultiByte. It supports more characters but in general is a little slower.
edited May 4 '16 at 12:26
Martin
12.2k53377
12.2k53377
answered Jan 13 '14 at 9:37
Notflip
2,10852655
2,10852655
add a comment |
add a comment |
up vote
12
down vote
The only thing I would add to these amazing answers is to emphasize on saving your files in utf8 encoding, i have noticed that browsers accept this property over setting utf8 as your code encoding. Any decent text editor will show you this, for example Notepad++ has a menu option for file enconding, it shows you the current encoding and enables you to change it. For all my php files I use utf8 without BOM.
Sometime ago i had someone ask me to add utf8 support for a php/mysql application designed by someone else, i noticed that all files were encoded in ANSI, so I had to use ICONV to convert all files, change the database tables to use the utf8 charset and utf8_general_ci collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier otherwise you have to use charset=utf8 in the connection string) and change string functions to use the php multibyte string functions equivalent.
add a comment |
up vote
12
down vote
The only thing I would add to these amazing answers is to emphasize on saving your files in utf8 encoding, i have noticed that browsers accept this property over setting utf8 as your code encoding. Any decent text editor will show you this, for example Notepad++ has a menu option for file enconding, it shows you the current encoding and enables you to change it. For all my php files I use utf8 without BOM.
Sometime ago i had someone ask me to add utf8 support for a php/mysql application designed by someone else, i noticed that all files were encoded in ANSI, so I had to use ICONV to convert all files, change the database tables to use the utf8 charset and utf8_general_ci collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier otherwise you have to use charset=utf8 in the connection string) and change string functions to use the php multibyte string functions equivalent.
add a comment |
up vote
12
down vote
up vote
12
down vote
The only thing I would add to these amazing answers is to emphasize on saving your files in utf8 encoding, i have noticed that browsers accept this property over setting utf8 as your code encoding. Any decent text editor will show you this, for example Notepad++ has a menu option for file enconding, it shows you the current encoding and enables you to change it. For all my php files I use utf8 without BOM.
Sometime ago i had someone ask me to add utf8 support for a php/mysql application designed by someone else, i noticed that all files were encoded in ANSI, so I had to use ICONV to convert all files, change the database tables to use the utf8 charset and utf8_general_ci collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier otherwise you have to use charset=utf8 in the connection string) and change string functions to use the php multibyte string functions equivalent.
The only thing I would add to these amazing answers is to emphasize on saving your files in utf8 encoding, i have noticed that browsers accept this property over setting utf8 as your code encoding. Any decent text editor will show you this, for example Notepad++ has a menu option for file enconding, it shows you the current encoding and enables you to change it. For all my php files I use utf8 without BOM.
Sometime ago i had someone ask me to add utf8 support for a php/mysql application designed by someone else, i noticed that all files were encoded in ANSI, so I had to use ICONV to convert all files, change the database tables to use the utf8 charset and utf8_general_ci collate, add 'SET NAMES utf8' to the database abstraction layer after the connection (if using 5.3.6 or earlier otherwise you have to use charset=utf8 in the connection string) and change string functions to use the php multibyte string functions equivalent.
edited Jun 17 '15 at 0:20
Funk Forty Niner
80.4k124799
80.4k124799
answered Sep 10 '14 at 3:39
Puerto AGP
19329
19329
add a comment |
add a comment |
up vote
8
down vote
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
add a comment |
up vote
8
down vote
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
add a comment |
up vote
8
down vote
up vote
8
down vote
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
answered Nov 10 '08 at 21:29
JW.
35.8k2796116
35.8k2796116
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
add a comment |
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
Great tip about the func_overload setting - allows for minimal modification to existing code.
– Simon East
Jan 15 '14 at 4:56
4
4
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
Just be careful -- some code might actually be relying on the one-byte-per-character nature of the standard string functions.
– JW.
Jan 15 '14 at 18:18
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.
– Simba
Feb 7 '17 at 13:08
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.
– Simba
Feb 7 '17 at 13:08
add a comment |
up vote
8
down vote
I have just went through the same issue and found a good solution at PHP manuals.
I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %sn", $mysqli->error);
} else {
printf("Current character set: %sn", $mysqli->character_set_name());
}
View Source
2
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.
– Funk Forty Niner
Jan 21 '17 at 14:16
@FunkFortyNiner Beware:set_charset("utf8")
may work but will behave differently (see the remarks about the difference betweenutf8
andutf8mb4
and the mysql version history). Useutf8
if you have to AND ONLY if you know what you're doing!
– Martin Hennings
Apr 24 at 10:09
add a comment |
up vote
8
down vote
I have just went through the same issue and found a good solution at PHP manuals.
I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %sn", $mysqli->error);
} else {
printf("Current character set: %sn", $mysqli->character_set_name());
}
View Source
2
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.
– Funk Forty Niner
Jan 21 '17 at 14:16
@FunkFortyNiner Beware:set_charset("utf8")
may work but will behave differently (see the remarks about the difference betweenutf8
andutf8mb4
and the mysql version history). Useutf8
if you have to AND ONLY if you know what you're doing!
– Martin Hennings
Apr 24 at 10:09
add a comment |
up vote
8
down vote
up vote
8
down vote
I have just went through the same issue and found a good solution at PHP manuals.
I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %sn", $mysqli->error);
} else {
printf("Current character set: %sn", $mysqli->character_set_name());
}
View Source
I have just went through the same issue and found a good solution at PHP manuals.
I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %sn", $mysqli->error);
} else {
printf("Current character set: %sn", $mysqli->character_set_name());
}
View Source
edited Jan 21 '17 at 14:24
Funk Forty Niner
80.4k124799
80.4k124799
answered May 5 '15 at 21:36
Abdul Sadik Yalcin
7532827
7532827
2
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.
– Funk Forty Niner
Jan 21 '17 at 14:16
@FunkFortyNiner Beware:set_charset("utf8")
may work but will behave differently (see the remarks about the difference betweenutf8
andutf8mb4
and the mysql version history). Useutf8
if you have to AND ONLY if you know what you're doing!
– Martin Hennings
Apr 24 at 10:09
add a comment |
2
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.
– Funk Forty Niner
Jan 21 '17 at 14:16
@FunkFortyNiner Beware:set_charset("utf8")
may work but will behave differently (see the remarks about the difference betweenutf8
andutf8mb4
and the mysql version history). Useutf8
if you have to AND ONLY if you know what you're doing!
– Martin Hennings
Apr 24 at 10:09
2
2
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.– Funk Forty Niner
Jan 21 '17 at 14:16
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.– Funk Forty Niner
Jan 21 '17 at 14:16
@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!– Martin Hennings
Apr 24 at 10:09
@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!– Martin Hennings
Apr 24 at 10:09
add a comment |
up vote
6
down vote
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
add a comment |
up vote
6
down vote
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
add a comment |
up vote
6
down vote
up vote
6
down vote
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
Unicode support in PHP is still a huge mess. While it's capable of converting an ISO8859 string (which it uses internally) to utf8, it lacks the capability to work with unicode strings natively, which means all the string processing functions will mangle and corrupt your strings. So you have to either use a separate library for proper utf8 support, or rewrite all the string handling functions yourself.
The easy part is just specifying the charset in HTTP headers and in the database and such, but none of that matters if your PHP code doesn't output valid UTF8. That's the hard part, and PHP gives you virtually no help there. (I think PHP6 is supposed to fix the worst of this, but that's still a while away)
edited Feb 11 '14 at 19:49
Chuck Burgess
9,99953372
9,99953372
answered Nov 10 '08 at 21:48
jalf
205k42293514
205k42293514
add a comment |
add a comment |
up vote
5
down vote
The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:
// storage
// debian. apparently already utf-8
// retrieval
// the mysql database was stored in utf-8,
// but apparently php was requesting iso. this worked:
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');
// delivery
// php.ini did not have a default charset,
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');
// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.
// processing
// changed a few commands in php, like substr,
// to mb_substr
that was all !
add a comment |
up vote
5
down vote
The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:
// storage
// debian. apparently already utf-8
// retrieval
// the mysql database was stored in utf-8,
// but apparently php was requesting iso. this worked:
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');
// delivery
// php.ini did not have a default charset,
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');
// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.
// processing
// changed a few commands in php, like substr,
// to mb_substr
that was all !
add a comment |
up vote
5
down vote
up vote
5
down vote
The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:
// storage
// debian. apparently already utf-8
// retrieval
// the mysql database was stored in utf-8,
// but apparently php was requesting iso. this worked:
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');
// delivery
// php.ini did not have a default charset,
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');
// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.
// processing
// changed a few commands in php, like substr,
// to mb_substr
that was all !
The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:
// storage
// debian. apparently already utf-8
// retrieval
// the mysql database was stored in utf-8,
// but apparently php was requesting iso. this worked:
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');
// delivery
// php.ini did not have a default charset,
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');
// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.
// processing
// changed a few commands in php, like substr,
// to mb_substr
that was all !
answered Jan 14 '11 at 16:13
commonpike
5,01413846
5,01413846
add a comment |
add a comment |
up vote
5
down vote
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
add a comment |
up vote
5
down vote
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
add a comment |
up vote
5
down vote
up vote
5
down vote
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
If you want MySQL server to decide character set, and not PHP as a client (old behaviour; preferred, in my opinion), try adding skip-character-set-client-handshake
to your my.cnf
, under [mysqld]
, and restart mysql
.
This may cause troubles in case you're using anything other than UTF8.
answered Feb 11 '15 at 23:52
Nikola Tulimirovic
54959
54959
add a comment |
add a comment |
protected by hjpotter92 Jan 6 '14 at 12:57
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
8
Here is an overview about all encoding faults you can possibly make: sebastianviereck.de/en/…
– Sebastian Viereck
Jan 27 '13 at 10:29
12
Here's an introduction to encodings in general and encodings in PHP in particular: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text
– deceze♦
Jul 9 '13 at 19:33
Some recent discussions about PHP 7 indicate that there are no changes in the "officially abandoned" position of 2010... There are something more about "PHP7 and UTF-8"?
– Peter Krauss
Sep 23 '15 at 6:02
This problem is common. But there is no shortcut solution, you will have to setup
utf-8
for each of them seprately - MySQL 5, PHP 5 OR Apache 2.– Manish Shrivastava
Jan 18 '17 at 14:00