Codeigniterで文字コード「Shift-JIS」のお問い合わせフォームを作成したら文字化けた・・・。
具体的な現象として、Codeigniterの関数でPOSTすると値が空になってしまう。
例
$this->input->post(); set_value();
原因としては、PHPのバージョンが原因でした。
以下、原因の箇所
$str = htmlspecialchars($str);
htmlspecialchars()関数は、変換に使用されるエンコーディングを省略した場合にデフォルト値を、PHP 5.4.0 より前のバージョンでは ISO-8859-1、そして PHP 5.4.0 以降では UTF-8 とする。
参考
http://www.php.net/manual/ja/function.htmlspecialchars.php
開発環境が、PHP5.4以上を使用していたため、
Codeigniter関数内では、htmlspecialchars()がデフォルト文字コードUTF-8 として
処理するため、POSTの値が消えてしまっていたみたいです。
解決策として、
application/helpers に以下MY_form_helper.phpとか名前を付けたファイルを配置して、中に以下の記述を行う。
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('form_prep'))
{
function form_prep($str = '', $field_name = '')
{
static $prepped_fields = array();
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $str;
}
if ($str === '')
{
return '';
}
if (isset($prepped_fields[$field_name]))
{
return $str;
}
// php5.4以降のhtmlspecialchars()のデフォルト文字コードの違い
// application/config/config.php の charset を出力
$CI = get_instance();
$config = $CI->config->config;
$str = htmlspecialchars($str, ENT_QUOTES, $config['charset']);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'", """), $str);
if ($field_name != '')
{
$prepped_fields[$field_name] = $field_name;
}
return $str;
}
}
これで解決するのではないのでしょうか?
ではまたノシ