EN49

Page 280

Chapter 48: UTF-8 Section 48.1: Input 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 consistently. There's really no way around this, as malicious clients can submit data in whatever encoding they want. $string = $_REQUEST['user_comment']; if (!mb_check_encoding($string, 'UTF-8')) { // the string is not UTF-8, so re-encode it. $actualEncoding = mb_detect_encoding($string); $string = mb_convert_encoding($string, 'UTF-8', $actualEncoding); }

If you're using HTML5 then you can ignore this last point. You want all data sent to you by browsers to be in UTF-8. The only reliable way to do this is to add the accept-charset attribute to all of your <form> tags like so: <form action="somepage.php" accept-charset="UTF-8">

Section 48.2: Output If your application transmits text to other systems, they will also need to be informed of the character encoding. In PHP, you can use the default_charset option in php.ini, or manually issue the Content-Type MIME header yourself. This is the preferred method when targeting modern browsers. header('Content-Type: text/html; charset=utf-8');

If you are unable to set the response headers, then you can also set the encoding in an HTML document with HTML metadata. HTML5 <meta charset="utf-8">

Older versions of HTML <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Section 48.3: Data Storage and Access This topic speciďŹ cally talks about UTF-8 and considerations for using it with a database. If you want more information about using databases in PHP then checkout this topic. Storing Data in a MySQL Database: 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.

GoalKicker.com – PHP Notes for Professionals

267


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.