文字化け解消!UTF-8 で PHP を使う

前回の設定編にて、「もし UTF-8 を使うのでしたら...」なんて人事のように書いていましたが、実際自分が EUC-JP ではなく、UTF-8 を使う状況になったので、ここに設定方法を書いておきます。私が利用しているホスティングサイト(Bluehost.com)の環境は PHP 4.4.2+MySQL4.1.20 (2006/7/29現在)で、MySQLがUTF-8をデフォルトキャラクターとしています。それにあわせて、PHP も UTF-8 で組もうと考えました。

設定は次のとおり:

.htaccess

<IfModule mod_php4.c>
php_value default_charset UTF-8
php_value mbstring.func_overload 7
php_value mbstring.language Japanese
php_value mbstring.internal_encoding UTF-8
php_flag  mbstring.encoding_translation On
php_value mbstring.detect_order UTF-8
php_value mbstring.http_input auto
php_value mbstring.http_output pass
</IfModule>

要はこれだけです。

その他、コード上で気を付ける点としては、次のように htmlentities にてHTMLエンティティの変換を行う時に、"UTF-8" を指定することを忘れないようにすることです。

function quote_smart($value) {
    if (get_magic_quotes_gpc()) {
        $value = stripslashes($value);
    }
    if (!is_numeric($value)) {
        $value = mysql_real_escape_string($value);
    }
    return htmlentities( $value, ENT_QUOTES, "UTF-8" );
}

function save_comments() {
  $link = mysql_connect('localhost', 'user name here', 'your password here')
    or die('Could not connect: ' . mysql_error());
  mysql_select_db('db name') or die('Could not select database');

  $query = sprintf (
    "INSERT INTO comments (foo,bar) VALUES('%s','%s')",
    quote_smart(date("Y/m/d H:i:s")),
    quote_smart($_POST['bar'])
  );

  $result = mysql_query($query)
    or die('Query failed: ' . mysql_error());
  mysql_close($link);
}

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Web/DB プログラミング徹底解説