Google+ Followers

2018年10月11日 星期四

PHP 開發筆記 - 判斷瀏覽器語系機制

就 Javascript 來說,很方便:

var userLanguage = navigator.language || navigator.userLanguage;

而 server site 就靠 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 啦,但他的格式還會有語系偏好比重,需要小小處理一番:

//
// $_SERVER['HTTP_ACCEPT_LANGUAGE'] == 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7';
//
function _detect_browser_language($_SERVER_VAR, $system_prefer = array( 'en' => 1, 'cn' => 1 )) {
if (isset($_SERVER_VAR['HTTP_ACCEPT_LANGUAGE'])) {
$langs = array();
foreach(explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $entry) {
$t1 = explode(';', $entry);
$cnt = count($t1);
if ($cnt == 2) {
$t2 = explode('=', $t1[1]);
if (count($t2) == 2)
array_push($langs, array($t1[0], floatval($t2[1])));
else
array_push($langs, array($t1[0], 1.0));
} else if ($cnt == 1)
array_push($langs, array($t1[0], 1.0));
}
function lang_prefer_sort($a, $b) {
if( $a[1] == $b[1] ) return 0;
if( $a[1] > $b[1] ) return -1;
return 1;
}
usort($langs, 'lang_prefer_sort');
foreach($langs as $lang_info) {
if (is_array($lang_info)) {
if (isset($system_prefer[$lang_info[0]]))
return $lang_info[0];
$checker = explode('-', $lang_info[0]);
if (count($checker) == 2) {
if (isset($system_prefer[$checker[0]]))
return $checker[0];
else if ($checker[0] == 'zh')
return 'cn';
}
}
}
}
return 'en';
}

沒有留言:

張貼留言