在開發多語系網站時,如何根據用戶偏好或瀏覽器設定自動顯示對應語言版本,是常見的需求。本文介紹一個實用的 PHP 類別 UserLang,能夠自動偵測用戶的語言偏好,並支援手動切換語言,預設支援英文、簡體中文與繁體中文三種語言。
Accept-Language 進行判斷。en(英文)、sc(簡體中文)、tc(繁體中文)。<?php
class UserLang {
private $name = 'userlang'; // Cookie 名稱
private $expire = 2592000; // Cookie 過期時間(秒),預設 30 天
public function __construct($name = '', $expire = null) {
if ($name !== '') $this->name = $name;
if (is_numeric($expire) && $expire > 0) $this->expire = intval($expire);
}
// 取得目前語言
public function get() {
if (isset($_COOKIE[$this->name])) {
return $_COOKIE[$this->name];
}
return $this->getAcceptLanguage();
}
// 設定語言
public function set($lang = '') {
$lang = strtolower($lang);
if (in_array($lang, ['en', 'sc', 'tc'])) {
setcookie($this->name, $lang, time() + $this->expire);
}
}
// 解析 Accept-Language 標頭
private function getAcceptLanguage() {
$lang = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '');
if (in_array(substr($lang, 0, 5), ['zh-tw', 'zh_hk'])) return 'tc';
if (in_array(substr($lang, 0, 5), ['zh-cn', 'zh-sg'])) return 'sc';
return 'en';
}
}
?>
<?php
require 'UserLang.class.php';
$obj = new UserLang('sitelang', 3600); // Cookie 名稱 sitelang,有效期 1 小時
echo $obj->get() . '<br>'; // 輸出目前語言代碼
?>
此類別適合用於多語系網站的語言自動偵測與切換功能,例如:
透過封裝 Cookie 讀寫與 HTTP 標頭解析邏輯,UserLang 讓多語系語言處理變得簡潔易維護,是 PHP 開發多語系網站的實用工具。