Remove incorrect script path.
[htmlpurifier.git] / docs / enduser-utf8.html
blob88a48a7028a511a80cf4f4bc2068054e43148b48
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6 <meta name="description" content="Describes the rationale for using UTF-8, the ramifications otherwise, and how to make the switch." />
7 <link rel="stylesheet" type="text/css" href="./style.css" />
8 <style type="text/css">
9 .minor td {font-style:italic;}
10 </style>
12 <title>UTF-8: The Secret of Character Encoding - HTML Purifier</title>
14 <!-- Note to users: this document, though professing to be UTF-8, attempts
15 to use only ASCII characters, because most webservers are configured
16 to send HTML as ISO-8859-1. So I will, many times, go against my
17 own advice for sake of portability. -->
19 </head><body>
21 <h1>UTF-8: The Secret of Character Encoding</h1>
23 <div id="filing">Filed under End-User</div>
24 <div id="index">Return to the <a href="index.html">index</a>.</div>
25 <div id="home"><a href="http://htmlpurifier.org/">HTML Purifier</a> End-User Documentation</div>
27 <p>Character encoding and character sets are not that
28 difficult to understand, but so many people blithely stumble
29 through the worlds of programming without knowing what to actually
30 do about it, or say &quot;Ah, it's a job for those <em>internationalization</em>
31 experts.&quot; No, it is not! This document will walk you through
32 determining the encoding of your system and how you should handle
33 this information. It will stay away from excessive discussion on
34 the internals of character encoding.</p>
36 <p>This document is not designed to be read in its entirety: it will
37 slowly introduce concepts that build on each other: you need not get to
38 the bottom to have learned something new. However, I strongly
39 recommend you read all the way to <strong>Why UTF-8?</strong>, because at least
40 at that point you'd have made a conscious decision not to migrate,
41 which can be a rewarding (but difficult) task.</p>
43 <blockquote class="aside">
44 <div class="label">Asides</div>
45 <p>Text in this formatting is an <strong>aside</strong>,
46 interesting tidbits for the curious but not strictly necessary material to
47 do the tutorial. If you read this text, you'll come out
48 with a greater understanding of the underlying issues.</p>
49 </blockquote>
51 <h2>Table of Contents</h2>
53 <ol id="toc">
54 <li><a href="#findcharset">Finding the real encoding</a></li>
55 <li><a href="#findmetacharset">Finding the embedded encoding</a></li>
56 <li><a href="#fixcharset">Fixing the encoding</a><ol>
57 <li><a href="#fixcharset-none">No embedded encoding</a></li>
58 <li><a href="#fixcharset-diff">Embedded encoding disagrees</a></li>
59 <li><a href="#fixcharset-server">Changing the server encoding</a><ol>
60 <li><a href="#fixcharset-server-php">PHP header() function</a></li>
61 <li><a href="#fixcharset-server-phpini">PHP ini directive</a></li>
62 <li><a href="#fixcharset-server-nophp">Non-PHP</a></li>
63 <li><a href="#fixcharset-server-htaccess">.htaccess</a></li>
64 <li><a href="#fixcharset-server-ext">File extensions</a></li>
65 </ol></li>
66 <li><a href="#fixcharset-xml">XML</a></li>
67 <li><a href="#fixcharset-internals">Inside the process</a></li>
68 </ol></li>
69 <li><a href="#whyutf8">Why UTF-8?</a><ol>
70 <li><a href="#whyutf8-i18n">Internationalization</a></li>
71 <li><a href="#whyutf8-user">User-friendly</a></li>
72 <li><a href="#whyutf8-forms">Forms</a><ol>
73 <li><a href="#whyutf8-forms-urlencoded">application/x-www-form-urlencoded</a></li>
74 <li><a href="#whyutf8-forms-multipart">multipart/form-data</a></li>
75 </ol></li>
76 <li><a href="#whyutf8-support">Well supported</a></li>
77 <li><a href="#whyutf8-htmlpurifier">HTML Purifiers</a></li>
78 </ol></li>
79 <li><a href="#migrate">Migrate to UTF-8</a><ol>
80 <li><a href="#migrate-db">Configuring your database</a><ol>
81 <li><a href="#migrate-db-legit">Legit method</a></li>
82 <li><a href="#migrate-db-binary">Binary</a></li>
83 </ol></li>
84 <li><a href="#migrate-editor">Text editor</a></li>
85 <li><a href="#migrate-bom">Byte Order Mark (headers already sent!)</a></li>
86 <li><a href="#migrate-fonts">Fonts</a><ol>
87 <li><a href="#migrate-fonts-obscure">Obscure scripts</a></li>
88 <li><a href="#migrate-fonts-occasional">Occasional use</a></li>
89 </ol></li>
90 <li><a href="#migrate-variablewidth">Dealing with variable width in functions</a></li>
91 </ol></li>
92 <li><a href="#externallinks">Further Reading</a></li>
93 </ol>
95 <h2 id="findcharset">Finding the real encoding</h2>
97 <p>In the beginning, there was ASCII, and things were simple. But they
98 weren't good, for no one could write in Cyrillic or Thai. So there
99 exploded a proliferation of character encodings to remedy the problem
100 by extending the characters ASCII could express. This ridiculously
101 simplified version of the history of character encodings shows us that
102 there are now many character encodings floating around.</p>
104 <blockquote class="aside">
105 <p>A <strong>character encoding</strong> tells the computer how to
106 interpret raw zeroes and ones into real characters. It
107 usually does this by pairing numbers with characters.</p>
108 <p>There are many different types of character encodings floating
109 around, but the ones we deal most frequently with are ASCII,
110 8-bit encodings, and Unicode-based encodings.</p>
111 <ul>
112 <li><strong>ASCII</strong> is a 7-bit encoding based on the
113 English alphabet.</li>
114 <li><strong>8-bit encodings</strong> are extensions to ASCII
115 that add a potpourri of useful, non-standard characters
116 like &eacute; and &aelig;. They can only add 127 characters,
117 so usually only support one script at a time. When you
118 see a page on the web, chances are it's encoded in one
119 of these encodings.</li>
120 <li><strong>Unicode-based encodings</strong> implement the
121 Unicode standard and include UTF-8, UCS-2 and UTF-16.
122 They go beyond 8-bits (the first two are variable length,
123 while the second one uses 16-bits), and support almost
124 every language in the world. UTF-8 is gaining traction
125 as the dominant international encoding of the web.</li>
126 </ul>
127 </blockquote>
129 <p>The first step of our journey is to find out what the encoding of
130 your website is. The most reliable way is to ask your
131 browser:</p>
133 <dl>
134 <dt>Mozilla Firefox</dt>
135 <dd>Tools &gt; Page Info: Encoding</dd>
136 <dt>Internet Explorer</dt>
137 <dd>View &gt; Encoding: bulleted item is unofficial name</dd>
138 </dl>
140 <p>Internet Explorer won't give you the MIME (i.e. useful/real) name of the
141 character encoding, so you'll have to look it up using their description.
142 Some common ones:</p>
144 <table class="table">
145 <thead><tr>
146 <th>IE's Description</th>
147 <th>Mime Name</th>
148 </tr></thead>
149 <tbody>
150 <tr><th colspan="2">Windows</th></tr>
151 <tr><td>Arabic (Windows)</td><td>Windows-1256</td></tr>
152 <tr><td>Baltic (Windows)</td><td>Windows-1257</td></tr>
153 <tr><td>Central European (Windows)</td><td>Windows-1250</td></tr>
154 <tr><td>Cyrillic (Windows)</td><td>Windows-1251</td></tr>
155 <tr><td>Greek (Windows)</td><td>Windows-1253</td></tr>
156 <tr><td>Hebrew (Windows)</td><td>Windows-1255</td></tr>
157 <tr><td>Thai (Windows)</td><td>TIS-620</td></tr>
158 <tr><td>Turkish (Windows)</td><td>Windows-1254</td></tr>
159 <tr><td>Vietnamese (Windows)</td><td>Windows-1258</td></tr>
160 <tr><td>Western European (Windows)</td><td>Windows-1252</td></tr>
161 </tbody>
162 <tbody>
163 <tr><th colspan="2">ISO</th></tr>
164 <tr><td>Arabic (ISO)</td><td>ISO-8859-6</td></tr>
165 <tr><td>Baltic (ISO)</td><td>ISO-8859-4</td></tr>
166 <tr><td>Central European (ISO)</td><td>ISO-8859-2</td></tr>
167 <tr><td>Cyrillic (ISO)</td><td>ISO-8859-5</td></tr>
168 <tr class="minor"><td>Estonian (ISO)</td><td>ISO-8859-13</td></tr>
169 <tr class="minor"><td>Greek (ISO)</td><td>ISO-8859-7</td></tr>
170 <tr><td>Hebrew (ISO-Logical)</td><td>ISO-8859-8-l</td></tr>
171 <tr><td>Hebrew (ISO-Visual)</td><td>ISO-8859-8</td></tr>
172 <tr class="minor"><td>Latin 9 (ISO)</td><td>ISO-8859-15</td></tr>
173 <tr class="minor"><td>Turkish (ISO)</td><td>ISO-8859-9</td></tr>
174 <tr><td>Western European (ISO)</td><td>ISO-8859-1</td></tr>
175 </tbody>
176 <tbody>
177 <tr><th colspan="2">Other</th></tr>
178 <tr><td>Chinese Simplified (GB18030)</td><td>GB18030</td></tr>
179 <tr><td>Chinese Simplified (GB2312)</td><td>GB2312</td></tr>
180 <tr><td>Chinese Simplified (HZ)</td><td>HZ</td></tr>
181 <tr><td>Chinese Traditional (Big5)</td><td>Big5</td></tr>
182 <tr><td>Japanese (Shift-JIS)</td><td>Shift_JIS</td></tr>
183 <tr><td>Japanese (EUC)</td><td>EUC-JP</td></tr>
184 <tr><td>Korean</td><td>EUC-KR</td></tr>
185 <tr><td>Unicode (UTF-8)</td><td>UTF-8</td></tr>
186 </tbody>
187 </table>
189 <p>Internet Explorer does not recognize some of the more obscure
190 character encodings, and having to lookup the real names with a table
191 is a pain, so I recommend using Mozilla Firefox to find out your
192 character encoding.</p>
194 <h2 id="findmetacharset">Finding the embedded encoding</h2>
196 <p>At this point, you may be asking, &quot;Didn't we already find out our
197 encoding?&quot; Well, as it turns out, there are multiple places where
198 a web developer can specify a character encoding, and one such place
199 is in a <code>META</code> tag:</p>
201 <pre>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;</pre>
203 <p>You'll find this in the <code>HEAD</code> section of an HTML document.
204 The text to the right of <code>charset=</code> is the &quot;claimed&quot;
205 encoding: the HTML claims to be this encoding, but whether or not this
206 is actually the case depends on other factors. For now, take note
207 if your <code>META</code> tag claims that either:</p>
209 <ol>
210 <li>The character encoding is the same as the one reported by the
211 browser,</li>
212 <li>The character encoding is different from the browser's, or</li>
213 <li>There is no <code>META</code> tag at all! (horror, horror!)</li>
214 </ol>
216 <h2 id="fixcharset">Fixing the encoding</h2>
218 <p class="aside">The advice given here is for pages being served as
219 vanilla <code>text/html</code>. Different practices must be used
220 for <code>application/xml</code> or <code>application/xml+xhtml</code>, see
221 <a href="http://www.w3.org/TR/2002/NOTE-xhtml-media-types-20020430/">W3C's
222 document on XHTML media types</a> for more information.</p>
224 <p>If your <code>META</code> encoding and your real encoding match,
225 savvy! You can skip this section. If they don't...</p>
227 <h3 id="fixcharset-none">No embedded encoding</h3>
229 <p>If this is the case, you'll want to add in the appropriate
230 <code>META</code> tag to your website. It's as simple as copy-pasting
231 the code snippet above and replacing UTF-8 with whatever is the mime name
232 of your real encoding.</p>
234 <blockquote class="aside">
235 <p>For all those skeptics out there, there is a very good reason
236 why the character encoding should be explicitly stated. When the
237 browser isn't told what the character encoding of a text is, it
238 has to guess: and sometimes the guess is wrong. Hackers can manipulate
239 this guess in order to slip XSS past filters and then fool the
240 browser into executing it as active code. A great example of this
241 is the <a href="http://shiflett.org/archive/177">Google UTF-7
242 exploit</a>.</p>
243 <p>You might be able to get away with not specifying a character
244 encoding with the <code>META</code> tag as long as your webserver
245 sends the right Content-Type header, but why risk it? Besides, if
246 the user downloads the HTML file, there is no longer any webserver
247 to define the character encoding.</p>
248 </blockquote>
250 <h3 id="fixcharset-diff">Embedded encoding disagrees</h3>
252 <p>This is an extremely common mistake: another source is telling
253 the browser what the
254 character encoding is and is overriding the embedded encoding. This
255 source usually is the Content-Type HTTP header that the webserver (i.e.
256 Apache) sends. A usual Content-Type header sent with a page might
257 look like this:</p>
259 <pre>Content-Type: text/html; charset=ISO-8859-1</pre>
261 <p>Notice how there is a charset parameter: this is the webserver's
262 way of telling a browser what the character encoding is, much like
263 the <code>META</code> tags we touched upon previously.</p>
265 <blockquote class="aside"><p>In fact, the <code>META</code> tag is
266 designed as a substitute for the HTTP header for contexts where
267 sending headers is impossible (such as locally stored files without
268 a webserver). Thus the name <code>http-equiv</code> (HTTP equivalent).
269 </p></blockquote>
271 <p>There are two ways to go about fixing this: changing the <code>META</code>
272 tag to match the HTTP header, or changing the HTTP header to match
273 the <code>META</code> tag. How do we know which to do? It depends
274 on the website's content: after all, headers and tags are only ways of
275 describing the actual characters on the web page.</p>
277 <p>If your website:</p>
279 <dl>
280 <dt>...only uses ASCII characters,</dt>
281 <dd>Either way is fine, but I recommend switching both to
282 UTF-8 (more on this later).</dd>
283 <dt>...uses special characters, and they display
284 properly,</dt>
285 <dd>Change the embedded encoding to the server encoding.</dd>
286 <dt>...uses special characters, but users often complain that
287 they come out garbled,</dt>
288 <dd>Change the server encoding to the embedded encoding.</dd>
289 </dl>
291 <p>Changing a META tag is easy: just swap out the old encoding
292 for the new. Changing the server (HTTP header) encoding, however,
293 is slightly more difficult.</p>
295 <h3 id="fixcharset-server">Changing the server encoding</h3>
297 <h4 id="fixcharset-server-php">PHP header() function</h4>
299 <p>The simplest way to handle this problem is to send the encoding
300 yourself, via your programming language. Since you're using HTML
301 Purifier, I'll assume PHP, although it's not too difficult to do
302 similar things in
303 <a href="http://www.w3.org/International/O-HTTP-charset#scripting">other
304 languages</a>. The appropriate code is:</p>
306 <pre><a href="http://php.net/function.header">header</a>('Content-Type:text/html; charset=UTF-8');</pre>
308 <p>...replacing UTF-8 with whatever your embedded encoding is.
309 This code must come before any output, so be careful about
310 stray whitespace in your application (i.e., any whitespace before
311 output excluding whitespace within &lt;?php ?&gt; tags).</p>
313 <h4 id="fixcharset-server-phpini">PHP ini directive</h4>
315 <p>PHP also has a neat little ini directive that can save you a
316 header call: <code><a href="http://php.net/ini.core#ini.default-charset">default_charset</a></code>. Using this code:</p>
318 <pre><a href="http://php.net/function.ini_set">ini_set</a>('default_charset', 'UTF-8');</pre>
320 <p>...will also do the trick. If PHP is running as an Apache module (and
321 not as FastCGI, consult
322 <a href="http://php.net/phpinfo">phpinfo</a>() for details), you can even use htaccess to apply this property
323 across many PHP files:</p>
325 <pre><a href="http://php.net/configuration.changes#configuration.changes.apache">php_value</a> default_charset &quot;UTF-8&quot;</pre>
327 <blockquote class="aside"><p>As with all INI directives, this can
328 also go in your php.ini file. Some hosting providers allow you to customize
329 your own php.ini file, ask your support for details. Use:</p>
330 <pre>default_charset = &quot;utf-8&quot;</pre></blockquote>
332 <h4 id="fixcharset-server-nophp">Non-PHP</h4>
334 <p>You may, for whatever reason, need to set the character encoding
335 on non-PHP files, usually plain ol' HTML files. Doing this
336 is more of a hit-or-miss process: depending on the software being
337 used as a webserver and the configuration of that software, certain
338 techniques may work, or may not work.</p>
340 <h4 id="fixcharset-server-htaccess">.htaccess</h4>
342 <p>On Apache, you can use an .htaccess file to change the character
343 encoding. I'll defer to
344 <a href="http://www.w3.org/International/questions/qa-htaccess-charset">W3C</a>
345 for the in-depth explanation, but it boils down to creating a file
346 named .htaccess with the contents:</p>
348 <pre><a href="http://httpd.apache.org/docs/1.3/mod/mod_mime.html#addcharset">AddCharset</a> UTF-8 .html</pre>
350 <p>Where UTF-8 is replaced with the character encoding you want to
351 use and .html is a file extension that this will be applied to. This
352 character encoding will then be set for any file directly in
353 or in the subdirectories of directory you place this file in.</p>
355 <p>If you're feeling particularly courageous, you can use:</p>
357 <pre><a href="http://httpd.apache.org/docs/1.3/mod/core.html#adddefaultcharset">AddDefaultCharset</a> UTF-8</pre>
359 <p>...which changes the character set Apache adds to any document that
360 doesn't have any Content-Type parameters. This directive, which the
361 default configuration file sets to iso-8859-1 for security
362 reasons, is probably why your headers mismatch
363 with the <code>META</code> tag. If you would prefer Apache not to be
364 butting in on your character encodings, you can tell it not
365 to send anything at all:</p>
367 <pre><a href="http://httpd.apache.org/docs/1.3/mod/core.html#adddefaultcharset">AddDefaultCharset</a> Off</pre>
369 <p>...making your internal charset declaration (usually the <code>META</code> tags)
370 the sole source of character encoding
371 information. In these cases, it is <em>especially</em> important to make
372 sure you have valid <code>META</code> tags on your pages and all the
373 text before them is ASCII.</p>
375 <blockquote class="aside"><p>These directives can also be
376 placed in httpd.conf file for Apache, but
377 in most shared hosting situations you won't be able to edit this file.
378 </p></blockquote>
380 <h4 id="fixcharset-server-ext">File extensions</h4>
382 <p>If you're not allowed to use .htaccess files, you can often
383 piggy-back off of Apache's default AddCharset declarations to get
384 your files in the proper extension. Here are Apache's default
385 character set declarations:</p>
387 <table class="table">
388 <thead><tr>
389 <th>Charset</th>
390 <th>File extension(s)</th>
391 </tr></thead>
392 <tbody>
393 <tr><td>ISO-8859-1</td><td>.iso8859-1 .latin1</td></tr>
394 <tr><td>ISO-8859-2</td><td>.iso8859-2 .latin2 .cen</td></tr>
395 <tr><td>ISO-8859-3</td><td>.iso8859-3 .latin3</td></tr>
396 <tr><td>ISO-8859-4</td><td>.iso8859-4 .latin4</td></tr>
397 <tr><td>ISO-8859-5</td><td>.iso8859-5 .latin5 .cyr .iso-ru</td></tr>
398 <tr><td>ISO-8859-6</td><td>.iso8859-6 .latin6 .arb</td></tr>
399 <tr><td>ISO-8859-7</td><td>.iso8859-7 .latin7 .grk</td></tr>
400 <tr><td>ISO-8859-8</td><td>.iso8859-8 .latin8 .heb</td></tr>
401 <tr><td>ISO-8859-9</td><td>.iso8859-9 .latin9 .trk</td></tr>
402 <tr><td>ISO-2022-JP</td><td>.iso2022-jp .jis</td></tr>
403 <tr><td>ISO-2022-KR</td><td>.iso2022-kr .kis</td></tr>
404 <tr><td>ISO-2022-CN</td><td>.iso2022-cn .cis</td></tr>
405 <tr><td>Big5</td><td>.Big5 .big5 .b5</td></tr>
406 <tr><td>WINDOWS-1251</td><td>.cp-1251 .win-1251</td></tr>
407 <tr><td>CP866</td><td>.cp866</td></tr>
408 <tr><td>KOI8-r</td><td>.koi8-r .koi8-ru</td></tr>
409 <tr><td>KOI8-ru</td><td>.koi8-uk .ua</td></tr>
410 <tr><td>ISO-10646-UCS-2</td><td>.ucs2</td></tr>
411 <tr><td>ISO-10646-UCS-4</td><td>.ucs4</td></tr>
412 <tr><td>UTF-8</td><td>.utf8</td></tr>
413 <tr><td>GB2312</td><td>.gb2312 .gb </td></tr>
414 <tr><td>utf-7</td><td>.utf7</td></tr>
415 <tr><td>EUC-TW</td><td>.euc-tw</td></tr>
416 <tr><td>EUC-JP</td><td>.euc-jp</td></tr>
417 <tr><td>EUC-KR</td><td>.euc-kr</td></tr>
418 <tr><td>shift_jis</td><td>.sjis</td></tr>
419 </tbody>
420 </table>
422 <p>So, for example, a file named <code>page.utf8.html</code> or
423 <code>page.html.utf8</code> will probably be sent with the UTF-8 charset
424 attached, the difference being that if there is an
425 <code>AddCharset charset .html</code> declaration, it will override
426 the .utf8 extension in <code>page.utf8.html</code> (precedence moves
427 from right to left). By default, Apache has no such declaration.</p>
429 <h4 id="fixcharset-server-iis">Microsoft IIS</h4>
431 <p>If anyone can contribute information on how to configure Microsoft
432 IIS to change character encodings, I'd be grateful.</p>
434 <h3 id="fixcharset-xml">XML</h3>
436 <p><code>META</code> tags are the most common source of embedded
437 encodings, but they can also come from somewhere else: XML
438 Declarations. They look like:</p>
440 <pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</pre>
442 <p>...and are most often found in XML documents (including XHTML).</p>
444 <p>For XHTML, this XML Declaration theoretically
445 overrides the <code>META</code> tag. In reality, this happens only when the
446 XHTML is actually served as legit XML and not HTML, which is almost always
447 never due to Internet Explorer's lack of support for
448 <code>application/xhtml+xml</code> (even though doing so is often
449 argued to be <a href="http://www.hixie.ch/advocacy/xhtml">good
450 practice</a> and is required by the XHTML 1.1 specification).</p>
452 <p>For XML, however, this XML Declaration is extremely important.
453 Since most webservers are not configured to send charsets for .xml files,
454 this is the only thing a parser has to go on. Furthermore, the default
455 for XML files is UTF-8, which often butts heads with more common
456 ISO-8859-1 encoding (you see this in garbled RSS feeds).</p>
458 <p>In short, if you use XHTML and have gone through the
459 trouble of adding the XML Declaration, make sure it jives
460 with your <code>META</code> tags (which should only be present
461 if served in text/html) and HTTP headers.</p>
463 <h3 id="fixcharset-internals">Inside the process</h3>
465 <p>This section is not required reading,
466 but may answer some of your questions on what's going on in all
467 this character encoding hocus pocus. If you're interested in
468 moving on to the next phase, skip this section.</p>
470 <p>A logical question that follows all of our wheeling and dealing
471 with multiple sources of character encodings is &quot;Why are there
472 so many options?&quot; To answer this question, we have to turn
473 back our definition of character encodings: they allow a program
474 to interpret bytes into human-readable characters.</p>
476 <p>Thus, a chicken-egg problem: a character encoding
477 is necessary to interpret the
478 text of a document. A <code>META</code> tag is in the text of a document.
479 The <code>META</code> tag gives the character encoding. How can we
480 determine the contents of a <code>META</code> tag, inside the text,
481 if we don't know it's character encoding? And how do we figure out
482 the character encoding, if we don't know the contents of the
483 <code>META</code> tag?</p>
485 <p>Fortunantely for us, the characters we need to write the
486 <code>META</code> are in ASCII, which is pretty much universal
487 over every character encoding that is in common use today. So,
488 all the web-browser has to do is parse all the way down until
489 it gets to the Content-Type tag, extract the character encoding
490 tag, then re-parse the document according to this new information.</p>
492 <p>Obviously this is complicated, so browsers prefer the simpler
493 and more efficient solution: get the character encoding from a
494 somewhere other than the document itself, i.e. the HTTP headers,
495 much to the chagrin of HTML authors who can't set these headers.</p>
497 <h2 id="whyutf8">Why UTF-8?</h2>
499 <p>So, you've gone through all the trouble of ensuring that your
500 server and embedded characters all line up properly and are
501 present. Good job: at
502 this point, you could quit and rest easy knowing that your pages
503 are not vulnerable to character encoding style XSS attacks.
504 However, just as having a character encoding is better than
505 having no character encoding at all, having UTF-8 as your
506 character encoding is better than having some other random
507 character encoding, and the next step is to convert to UTF-8.
508 But why?</p>
510 <h3 id="whyutf8-i18n">Internationalization</h3>
512 <p>Many software projects, at one point or another, suddenly realize
513 that they should be supporting more than one language. Even regular
514 usage in one language sometimes requires the occasional special character
515 that, without surprise, is not available in your character set. Sometimes
516 developers get around this by adding support for multiple encodings: when
517 using Chinese, use Big5, when using Japanese, use Shift-JIS, when
518 using Greek, etc. Other times, they use character references with great
519 zeal.</p>
521 <p>UTF-8, however, obviates the need for any of these complicated
522 measures. After getting the system to use UTF-8 and adjusting for
523 sources that are outside the hand of the browser (more on this later),
524 UTF-8 just works. You can use it for any language, even many languages
525 at once, you don't have to worry about managing multiple encodings,
526 you don't have to use those user-unfriendly entities.</p>
528 <h3 id="whyutf8-user">User-friendly</h3>
530 <p>Websites encoded in Latin-1 (ISO-8859-1) which ocassionally need
531 a special character outside of their scope often will use a character
532 entity reference to achieve the desired effect. For instance, &theta; can be
533 written <code>&amp;theta;</code>, regardless of the character encoding's
534 support of Greek letters.</p>
536 <p>This works nicely for limited use of special characters, but
537 say you wanted this sentence of Chinese text: &#28608;&#20809;,
538 &#36889;&#20841;&#20491;&#23383;&#26159;&#29978;&#40636;&#24847;&#24605;.
539 The ampersand encoded version would look like this:</p>
541 <pre>&amp;#28608;&amp;#20809;, &amp;#36889;&amp;#20841;&amp;#20491;&amp;#23383;&amp;#26159;&amp;#29978;&amp;#40636;&amp;#24847;&amp;#24605;</pre>
543 <p>Extremely inconvenient for those of us who actually know what
544 character entities are, totally unintelligible to poor users who don't!
545 Even the slightly more user-friendly, &quot;intelligible&quot; character
546 entities like <code>&amp;theta;</code> will leave users who are
547 uninterested in learning HTML scratching their heads. On the other
548 hand, if they see &theta; in an edit box, they'll know that it's a
549 special character, and treat it accordingly, even if they don't know
550 how to write that character themselves.</p>
552 <blockquote class="aside"><p>Wikipedia is a great case study for
553 an application that originally used ISO-8859-1 but switched to UTF-8
554 when it became far to cumbersome to support foreign languages. Bots
555 will now actually go through articles and convert character entities
556 to their corresponding real characters for the sake of user-friendliness
557 and searchability. See
558 <a href="http://meta.wikimedia.org/wiki/Help:Special_characters">Meta's
559 page on special characters</a> for more details.
560 </p></blockquote>
562 <h3 id="whyutf8-forms">Forms</h3>
564 <p>While we're on the tack of users, how do non-UTF-8 web forms deal
565 with characters that our outside of their character set? Rather than
566 discuss what UTF-8 does right, we're going to show what could go wrong
567 if you didn't use UTF-8 and people tried to use characters outside
568 of your character encoding.</p>
570 <p>The troubles are large, extensive, and extremely difficult to fix (or,
571 at least, difficult enough that if you had the time and resources to invest
572 in doing the fix, you would be probably better off migrating to UTF-8).
573 There are two types of form submission: <code>application/x-www-form-urlencoded</code>
574 which is used for GET and by default for POST, and <code>multipart/form-data</code>
575 which may be used by POST, and is required when you want to upload
576 files.</p>
578 <p>The following is a summarization of notes from
579 <a href="http://web.archive.org/web/20060427015200/ppewww.ph.gla.ac.uk/~flavell/charset/form-i18n.html">
580 <code>FORM</code> submission and i18n</a>. That document contains lots
581 of useful information, but is written in a rambly manner, so
582 here I try to get right to the point. (Note: the original has
583 disappeared off the web, so I am linking to the Web Archive copy.)</p>
585 <h4 id="whyutf8-forms-urlencoded"><code>application/x-www-form-urlencoded</code></h4>
587 <p>This is the Content-Type that GET requests must use, and POST requests
588 use by default. It involves the ubiquituous percent encoding format that
589 looks something like: <code>%C3%86</code>. There is no official way of
590 determining the character encoding of such a request, since the percent
591 encoding operates on a byte level, so it is usually assumed that it
592 is the same as the encoding the page containing the form was submitted
593 in. You'll run into very few problems if you only use characters in
594 the character encoding you chose.</p>
596 <p>However, once you start adding characters outside of your encoding
597 (and this is a lot more common than you may think: take curly
598 &quot;smart&quot; quotes from Microsoft as an example),
599 a whole manner of strange things start to happen. Depending on the
600 browser you're using, they might:</p>
602 <ul>
603 <li>Replace the unsupported characters with useless question marks,</li>
604 <li>Attempt to fix the characters (example: smart quotes to regular quotes),</li>
605 <li>Replace the character with a character entity reference, or</li>
606 <li>Send it anyway as a different character encoding mixed in
607 with the original encoding (usually Windows-1252 rather than
608 iso-8859-1 or UTF-8 interspersed in 8-bit)</li>
609 </ul>
611 <p>To properly guard against these behaviors, you'd have to sniff out
612 the browser agent, compile a database of different behaviors, and
613 take appropriate conversion action against the string (disregarding
614 a spate of extremely mysterious, random and devastating bugs Internet
615 Explorer manifests every once in a while). Or you could
616 use UTF-8 and rest easy knowing that none of this could possibly happen
617 since UTF-8 supports every character.</p>
619 <h4 id="whyutf8-forms-multipart"><code>multipart/form-data</code></h4>
621 <p>Multipart form submission takes away a lot of the ambiguity
622 that percent-encoding had: the server now can explicitly ask for
623 certain encodings, and the client can explicitly tell the server
624 during the form submission what encoding the fields are in.</p>
626 <p>There are two ways you go with this functionality: leave it
627 unset and have the browser send in the same encoding as the page,
628 or set it to UTF-8 and then do another conversion server-side.
629 Each method has deficiencies, especially the former.</p>
631 <p>If you tell the browser to send the form in the same encoding as
632 the page, you still have the trouble of what to do with characters
633 that are outside of the character encoding's range. The behavior, once
634 again, varies: Firefox 2.0 converts them to character entity references
635 while Internet Explorer 7.0 mangles them beyond intelligibility. For
636 serious internationalization purposes, this is not an option.</p>
638 <p>The other possibility is to set Accept-Encoding to UTF-8, which
639 begs the question: Why aren't you using UTF-8 for everything then?
640 This route is more palatable, but there's a notable caveat: your data
641 will come in as UTF-8, so you will have to explicitly convert it into
642 your favored local character encoding.</p>
644 <p>I object to this approach on idealogical grounds: you're
645 digging yourself deeper into
646 the hole when you could have been converting to UTF-8
647 instead. And, of course, you can't use this method for GET requests.</p>
649 <h3 id="whyutf8-support">Well supported</h3>
651 <p>Almost every modern browser in the wild today has full UTF-8 and Unicode
652 support: the number of troublesome cases can be counted with the
653 fingers of one hand, and these browsers usually have trouble with
654 other character encodings too. Problems users usually encounter stem
655 from the lack of appropriate fonts to display the characters (once
656 again, this applies to all character encodings and HTML entities) or
657 Internet Explorer's lack of intelligent font picking (which can be
658 worked around).</p>
660 <p>We will go into more detail about how to deal with edge cases in
661 the browser world in the Migration section, but rest assured that
662 converting to UTF-8, if done correctly, will not result in users
663 hounding you about broken pages.</p>
665 <h3 id="whyutf8-htmlpurifier">HTML Purifier</h3>
667 <p>And finally, we get to HTML Purifier. HTML Purifier is built to
668 deal with UTF-8: any indications otherwise are the result of an
669 encoder that converts text from your preferred encoding to UTF-8, and
670 back again. HTML Purifier never touches anything else, and leaves
671 it up to the module iconv to do the dirty work.</p>
673 <p>This approach, however, is not perfect. iconv is blithely unaware
674 of HTML character entities. HTML Purifier, in order to
675 protect against sophisticated escaping schemes, normalizes all character
676 and numeric entitie references before processing the text. This leads to
677 one important ramification:</p>
679 <p><strong>Any character that is not supported by the target character
680 set, regardless of whether or not it is in the form of a character
681 entity reference or a raw character, will be silently ignored.</strong></p>
683 <p>Example of this principle at work: say you have <code>&amp;theta;</code>
684 in your HTML, but the output is in Latin-1 (which, understandably,
685 does not understand Greek), the following process will occur (assuming you've
686 set the encoding correctly using %Core.Encoding):</p>
688 <ul>
689 <li>The <code>Encoder</code> will transform the text from ISO 8859-1 to UTF-8
690 (note that theta is preserved here since it doesn't actually use
691 any non-ASCII characters): <code>&amp;theta;</code></li>
692 <li>The <code>EntityParser</code> will transform all named and numeric
693 character entities to their corresponding raw UTF-8 equivalents:
694 <code>&theta;</code></li>
695 <li>HTML Purifier processes the code: <code>&theta;</code></li>
696 <li>The <code>Encoder</code> now transforms the text back from UTF-8
697 to ISO 8859-1. Since Greek is not supported by ISO 8859-1, it
698 will be either ignored or replaced with a question mark:
699 <code>?</code></li>
700 </ul>
702 <p>This behaviour is quite unsatisfactory. It is a deal-breaker for
703 international applications, and it can be mildly annoying for the provincial
704 soul who occasionally needs a special character. Since 1.4.0, HTML
705 Purifier has provided a slightly more palatable workaround using
706 %Core.EscapeNonASCIICharacters. The process now looks like:</p>
708 <ul>
709 <li>The <code>Encoder</code> transforms encoding to UTF-8: <code>&amp;theta;</code></li>
710 <li>The <code>EntityParser</code> transforms entities: <code>&theta;</code></li>
711 <li>HTML Purifier processes the code: <code>&theta;</code></li>
712 <li>The <code>Encoder</code> replaces all non-ASCII characters
713 with numeric entity reference: <code>&amp;#952;</code></li>
714 <li>For good measure, <code>Encoder</code> transforms encoding back to
715 original (which is strictly unnecessary for 99% of encodings
716 out there): <code>&amp;#952;</code> (remember, it's all ASCII!)</li>
717 </ul>
719 <p>...which means that this is only good for an occasional foray into
720 the land of Unicode characters, and is totally unacceptable for Chinese
721 or Japanese texts. The even bigger kicker is that, supposing the
722 input encoding was actually ISO-8859-7, which <em>does</em> support
723 theta, the character would get converted into a character entity reference
724 anyway! (The Encoder does not discriminate).</p>
726 <p>The current functionality is about where HTML Purifier will be for
727 the rest of eternity. HTML Purifier could attempt to preserve the original
728 form of the character references so that they could be substituted back in, only the
729 DOM extension kills them off irreversibly. HTML Purifier could also attempt
730 to be smart and only convert non-ASCII characters that weren't supported
731 by the target encoding, but that would require reimplementing iconv
732 with HTML awareness, something I will not do.</p>
734 <p>So there: either it's UTF-8 or crippled international support. Your pick! (and I'm
735 not being sarcastic here: some people could care less about other languages).</p>
737 <h2 id="migrate">Migrate to UTF-8</h2>
739 <p>So, you've decided to bite the bullet, and want to migrate to UTF-8.
740 Note that this is not for the faint-hearted, and you should expect
741 the process to take longer than you think it will take.</p>
743 <p>The general idea is that you convert all existing text to UTF-8,
744 and then you set all the headers and META tags we discussed earlier
745 to UTF-8. There are many ways going about doing this: you could
746 write a conversion script that runs through the database and re-encodes
747 everything as UTF-8 or you could do the conversion on the fly when someone
748 reads the page. The details depend on your system, but I will cover
749 some of the more subtle points of migration that may trip you up.</p>
751 <h3 id="migrate-db">Configuring your database</h3>
753 <p>Most modern databases, the most prominent open-source ones being MySQL
754 4.1+ and PostgreSQL, support character encodings. If you're switching
755 to UTF-8, logically speaking, you'd want to make sure your database
756 knows about the change too. There are some caveats though:</p>
758 <h4 id="migrate-db-legit">Legit method</h4>
760 <p>Standardization in terms of SQL syntax for specifying character
761 encodings is notoriously spotty. Refer to your respective database's
762 documentation on how to do this properly.</p>
764 <p>For <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html">MySQL</a>, <code>ALTER</code> will magically perform the
765 character encoding conversion for you. However, you have
766 to make sure that the text inside the column is what is says it is:
767 if you had put Shift-JIS in an ISO 8859-1 column, MySQL will irreversibly mangle
768 the text when you try to convert it to UTF-8. You'll have to convert
769 it to a binary field, convert it to a Shift-JIS field (the real encoding),
770 and then finally to UTF-8. Many a website had pages irreversibly mangled
771 because they didn't realize that they'd been deluding themselves about
772 the character encoding all along, don't become the next victim.</p>
774 <p>For <a href="http://www.postgresql.org/docs/8.2/static/multibyte.html">PostgreSQL</a>, there appears to be no direct way to change the
775 encoding of a database (as of 8.2). You will have to dump the data, and then reimport
776 it into a new table. Make sure that your client encoding is set properly:
777 this is how PostgreSQL knows to perform an encoding conversion.</p>
779 <p>Many times, you will be also asked about the &quot;collation&quot; of
780 the new column. Collation is how a DBMS sorts text, like ordering
781 B, C and A into A, B and C (the problem gets surprisingly complicated
782 when you get to languages like Thai and Japanese). If in doubt,
783 going with the default setting is usually a safe bet.</p>
785 <p>Once the conversion is all said and done, you still have to remember
786 to set the client encoding (your encoding) properly on each database
787 connection using <code>SET NAMES</code> (which is standard SQL and is
788 usually supported).</p>
790 <h4 id="migrate-db-binary">Binary</h4>
792 <p>Due to the abovementioned compatibility issues, a more interoperable
793 way of storing UTF-8 text is to stuff it in a binary datatype.
794 <code>CHAR</code> becomes <code>BINARY</code>, <code>VARCHAR</code> becomes
795 <code>VARBINARY</code> and <code>TEXT</code> becomes <code>BLOB</code>.
796 Doing so can save you some huge headaches:</p>
798 <ul>
799 <li>The syntax for binary data types is very portable,</li>
800 <li>MySQL 4.0 has <em>no</em> support for character encodings, so
801 if you want to support it you <em>have</em> to use binary,</li>
802 <li>MySQL, as of 5.1, has no support for four byte UTF-8 characters,
803 which represent characters beyond the basic multilingual
804 plane, and</li>
805 <li>You will never have to worry about your DBMS being too smart
806 and attempting to convert your text when you don't want it to.</li>
807 </ul>
809 <p>MediaWiki, a very prominent international application, uses binary fields
810 for storing their data because of point three.</p>
812 <p>There are drawbacks, of course:</p>
814 <ul>
815 <li>Database tools like PHPMyAdmin won't be able to offer you inline
816 text editing, since it is declared as binary,</li>
817 <li>It's not semantically correct: it's really text not binary
818 (lying to the database),</li>
819 <li>Unless you use the not-very-portable wizardry mentioned above,
820 you have to change the encoding yourself (usually, you'd do
821 it on the fly), and</li>
822 <li>You will not have collation.</li>
823 </ul>
825 <p>Choose based on your circumstances.</p>
827 <h3 id="migrate-editor">Text editor</h3>
829 <p>For more flat-file oriented systems, you will often be tasked with
830 converting reams of existing text and HTML files into UTF-8, as well as
831 making sure that all new files uploaded are properly encoded. Once again,
832 I can only point vaguely in the right direction for converting your
833 existing files: make sure you backup, make sure you use
834 <a href="http://php.net/ref.iconv">iconv</a>(), and
835 make sure you know what the original character encoding of the files
836 is (or are, depending on the tidiness of your system).</p>
838 <p>However, I can proffer more specific advice on the subject of
839 text editors. Many text editors have notoriously spotty Unicode support.
840 To find out how your editor is doing, you can check out <a
841 href="http://www.alanwood.net/unicode/utilities_editors.html">this list</a>
842 or <a href="http://en.wikipedia.org/wiki/Comparison_of_text_editors#Encoding_support">Wikipedia's list.</a>
843 I personally use Notepad++, which works like a charm when it comes to UTF-8.
844 Usually, you will have to <strong>explicitly</strong> tell the editor through some dialogue
845 (usually Save as or Format) what encoding you want it to use. An editor
846 will often offer &quot;Unicode&quot; as a method of saving, which is
847 ambiguous. Make sure you know whether or not they really mean UTF-8
848 or UTF-16 (which is another flavor of Unicode).</p>
850 <p>The two things to look out for are whether or not the editor
851 supports <strong>font mixing</strong> (multiple
852 fonts in one document) and whether or not it adds a <strong>BOM</strong>.
853 Font mixing is important because fonts rarely have support for every
854 language known to mankind: in order to be flexible, an editor must
855 be able to take a little from here and a little from there, otherwise
856 all your Chinese characters will come as nice boxes. We'll discuss
857 BOM below.</p>
859 <h3 id="migrate-bom">Byte Order Mark (headers already sent!)</h3>
861 <p>The BOM, or <a href="http://en.wikipedia.org/wiki/Byte_Order_Mark">Byte
862 Order Mark</a>, is a magical, invisible character placed at
863 the beginning of UTF-8 files to tell people what the encoding is and
864 what the endianness of the text is. It is also unnecessary.</p>
866 <p>Because it's invisible, it often
867 catches people by surprise when it starts doing things it shouldn't
868 be doing. For example, this PHP file:</p>
870 <pre><strong>BOM</strong>&lt;?php
871 header('Location: index.php');
872 ?&gt;</pre>
874 <p>...will fail with the all too familiar <strong>Headers already sent</strong>
875 PHP error. And because the BOM is invisible, this culprit will go unnoticed.
876 My suggestion is to only use ASCII in PHP pages, but if you must, make
877 sure the page is saved WITHOUT the BOM.</p>
879 <blockquote class="aside">
880 <p>The headers the error is referring to are <strong>HTTP headers</strong>,
881 which are sent to the browser before any HTML to tell it various
882 information. The moment any regular text (and yes, a BOM counts as
883 ordinary text) is output, the headers must be sent, and you are
884 not allowed to send anymore. Thus, the error.</p>
885 </blockquote>
887 <p>If you are reading in text files to insert into the middle of another
888 page, it is strongly advised (but not strictly necessary) that you replace out the UTF-8 byte
889 sequence for BOM <code>&quot;\xEF\xBB\xBF&quot;</code> before inserting it in,
890 via:</p>
892 <pre>$text = str_replace(&quot;\xEF\xBB\xBF&quot;, '', $text);</pre>
894 <h3 id="migrate-fonts">Fonts</h3>
896 <p>Generally speaking, people who are having trouble with fonts fall
897 into two categories:</p>
899 <ul>
900 <li>Those who want to
901 use an extremely obscure language for which there is very little
902 support even among native speakers of the language, and</li>
903 <li>Those where the primary language of the text is
904 well-supported but there are occasional characters
905 that aren't supported.</li>
906 </ul>
908 <p>Yes, there's always a chance where an English user happens across
909 a Sinhalese website and doesn't have the right font. But an English user
910 who happens not to have the right fonts probably has no business reading Sinhalese
911 anyway. So we'll deal with the other two edge cases.</p>
913 <h4 id="migrate-fonts-obscure">Obscure scripts</h4>
915 <p>If you run a Bengali website, you may get comments from users who
916 would like to read your website but get heaps of question marks or
917 other meaningless characters. Fixing this problem requires the
918 installation of a font or language pack which is often highly
919 dependent on what the language is. <a href="http://bn.wikipedia.org/wiki/%E0%A6%89%E0%A6%87%E0%A6%95%E0%A6%BF%E0%A6%AA%E0%A7%87%E0%A6%A1%E0%A6%BF%E0%A6%AF%E0%A6%BC%E0%A6%BE:Bangla_script_display_help">Here is an example</a>
920 of such a help file for the Bengali language, I am sure there are
921 others out there too. You just have to point users to the appropriate
922 help file.</p>
924 <h4 id="migrate-fonts-occasional">Occasional use</h4>
926 <p>A prime example of when you'll see some very obscure Unicode
927 characters embedded in what otherwise would be very bland ASCII are
928 letters of the
929 <a href="http://en.wikipedia.org/wiki/International_Phonetic_Alphabet">International
930 Phonetic Alphabet (IPA)</a>, use to designate pronounciations in a very standard
931 manner (you probably see them all the time in your dictionary). Your
932 average font probably won't have support for all of the IPA characters
933 like &#664; (bilabial click) or &#658; (voiced postalveolar fricative).
934 So what's a poor browser to do? Font mix! Smart browsers like Mozilla Firefox
935 and Internet Explorer 7 will borrow glyphs from other fonts in order
936 to make sure that all the characters display properly.</p>
938 <p>But what happens when the browser isn't smart and happens to be the
939 most widely used browser in the entire world? Microsoft IE 6
940 is not smart enough to borrow from other fonts when a character isn't
941 present, so more often than not you'll be slapped with a nice big &#65533;.
942 To get things to work, MSIE 6 needs a little nudge. You could configure it
943 to use a different font to render the text, but you can acheive the same
944 effect by selectively changing the font for blocks of special characters
945 to known good Unicode fonts.</p>
947 <p>Fortunantely, the folks over at Wikipedia have already done all the
948 heavy lifting for you. Get the CSS from the horses mouth here:
949 <a href="http://en.wikipedia.org/wiki/MediaWiki:Common.css">Common.css</a>,
950 and search for &quot;.IPA&quot; There are also a smattering of
951 other classes you can use for other purposes, check out
952 <a href="http://meta.wikimedia.org/wiki/Help:Special_characters#Displaying_Special_Characters">this page</a>
953 for more details. For you lazy ones, this should work:</p>
955 <pre>.Unicode {
956 font-family: Code2000, &quot;TITUS Cyberbit Basic&quot;, &quot;Doulos SIL&quot;,
957 &quot;Chrysanthi Unicode&quot;, &quot;Bitstream Cyberbit&quot;,
958 &quot;Bitstream CyberBase&quot;, Thryomanes, Gentium, GentiumAlt,
959 &quot;Lucida Grande&quot;, &quot;Arial Unicode MS&quot;, &quot;Microsoft Sans Serif&quot;,
960 &quot;Lucida Sans Unicode&quot;;
961 font-family /**/:inherit; /* resets fonts for everyone but IE6 */
962 }</pre>
964 <p>The standard usage goes along the lines of <code>&lt;span class=&quot;Unicode&quot;&gt;Crazy
965 Unicode stuff here&lt;/span&gt;</code>. Characters in the
966 <a href="http://en.wikipedia.org/wiki/Windows_Glyph_List_4">Windows Glyph List</a>
967 usually don't need to be fixed, but for anything else you probably
968 want to play it safe. Unless, of course, you don't care about IE6
969 users.</p>
971 <h3 id="migrate-variablewidth">Dealing with variable width in functions</h3>
973 <p>When people claim that PHP6 will solve all our Unicode problems, they're
974 misinformed. It will not fix any of the abovementioned troubles. It will,
975 however, fix the problem we are about to discuss: processing UTF-8 text
976 in PHP.</p>
978 <p>PHP (as of PHP5) is blithely unaware of the existence of UTF-8 (with a few
979 notable exceptions). Sometimes, this will cause problems, other times,
980 this won't. So far, we've avoided discussing the architecture of
981 UTF-8, so, we must first ask, what is UTF-8? Yes, it supports Unicode,
982 and yes, it is variable width. Other traits:</p>
984 <ul>
985 <li>Every character's byte sequence is unique and will never be found
986 inside the byte sequence of another character,</li>
987 <li>UTF-8 may use up to four bytes to encode a character,</li>
988 <li>UTF-8 text must be checked for well-formedness,</li>
989 <li>Pure ASCII is also valid UTF-8, and</li>
990 <li>Binary sorting will sort UTF-8 in the same order as Unicode.</li>
991 </ul>
993 <p>Each of these traits affect different domains of text processing
994 in different ways. It is beyond the scope of this document to explain
995 what precisely these implications are. PHPWact provides
996 a very good <a href="http://www.phpwact.org/php/i18n/utf-8">reference document</a>
997 on what to expect from each function, although coverage is spotty in
998 some areas. Their more general notes on
999 <a href="http://www.phpwact.org/php/i18n/charsets">character sets</a>
1000 are also worth looking at for information on UTF-8. Some rules of thumb
1001 when dealing with Unicode text:</p>
1003 <ul>
1004 <li>Do not EVER use functions that:<ul>
1005 <li>...convert case (strtolower, strtoupper, ucfirst, ucwords)</li>
1006 <li>...claim to be case-insensitive (str_ireplace, stristr, strcasecmp)</li>
1007 </ul></li>
1008 <li>Think twice before using functions that:<ul>
1009 <li>...count characters (strlen will return bytes, not characters;
1010 str_split and word_wrap may corrupt)</li>
1011 <li>...convert characters to entity references (UTF-8 doesn't need entities)</li>
1012 <li>...do very complex string processing (*printf)</li>
1013 </ul></li>
1014 </ul>
1016 <p>Note: this list applies to UTF-8 encoded text only: if you have
1017 a string that you are 100% sure is ASCII, be my guest and use
1018 <code>strtolower</code> (HTML Purifier uses this function.)</p>
1020 <p>Regardless, always think in bytes, not characters. If you use strpos()
1021 to find the position of a character, it will be in bytes, but this
1022 usually won't matter since substr() also operates with byte indices!</p>
1024 <p>You'll also need to make sure your UTF-8 is well-formed and will
1025 probably need replacements for some of these functions. I recommend
1026 using Harry Fuecks' <a href="http://phputf8.sourceforge.net/">PHP
1027 UTF-8</a> library, rather than use mb_string directly. HTML Purifier
1028 also defines a few useful UTF-8 compatible functions: check out
1029 <code>Encoder.php</code> in the <code>/library/HTMLPurifier/</code>
1030 directory.</p>
1032 <h2 id="externallinks">Further Reading</h2>
1034 <p>Well, that's it. Hopefully this document has served as a very
1035 practical springboard into knowledge of how UTF-8 works. You may have
1036 decided that you don't want to migrate yet: that's fine, just know
1037 what will happen to your output and what bug reports you may recieve.</p>
1039 <p>Many other developers have already discussed the subject of Unicode,
1040 UTF-8 and internationalization, and I would like to defer to them for
1041 a more in-depth look into character sets and encodings.</p>
1043 <ul>
1044 <li><a href="http://www.joelonsoftware.com/articles/Unicode.html">
1045 The Absolute Minimum Every Software Developer Absolutely,
1046 Positively Must Know About Unicode and Character Sets
1047 (No Excuses!)</a> by Joel Spolsky, provides a <em>very</em>
1048 good high-level look at Unicode and character sets in general.</li>
1049 <li><a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8 on Wikipedia</a>,
1050 provides a lot of useful details into the innards of UTF-8, although
1051 it may be a little off-putting to people who don't know much
1052 about Unicode to begin with.</li>
1053 </ul>
1055 </body>
1056 </html>