最近更新: 2008-02-14

PHP如何取得虛擬主機名稱及瀏覽器適用的地區語文資訊

在 HTTP 協定(RFC2612) 中提到, Host 可用於得知使用者存取主機資源時會使用的主機名稱,供 HTTP Server 判斷虛擬主機設置。Accept-Language 可用於得知使用者的地區語文清單。服務者可根據此清單內容,呈現最適用於使用者的地區語文內容。

在 PHP 中,可藉由全域變數 $_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME'] 取得 Host 內容。$_SERVER['HTTP_ACCEPT_LANGUAGE'] 取得瀏覽器適用的語文清單。

HTTP_HOST, SERVER_NAME should be the same. However, SERVER_NAME looks like only available in Apache2.

14.23 Host

Host = "Host" ":" host [ ":" port ] ; Section 3.2.2

A “host” without any trailing port information implies the default port for the service requested (e.g., “80” for an HTTP URL). For example, a request on the origin server for would properly include:

GET /pub/WWW/ HTTP/1.1
Host: www.w3.org

14.4 Accept-Language

The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. Language tags are defined in section 3.10.

Accept-Language = "Accept-Language" ":"
1#( language-range [ ";" "q" "=" qvalue ] )
language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )

Each language-range MAY be given an associated quality value which represents an estimate of the user's preference for the languages specified by that range. The quality value defaults to “q=1”. For example,

Accept-Language: da, en-gb;q=0.8, en;q=0.7
<?php
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['SERVER_NAME'];

$acceptLanguageList = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
 
if (preg_match('/en\-?/', $acceptLanguageList[0])) {
    echo 'Good morning';
}
else if (strpos('zh-cn', $acceptLanguageList[0]) != false) {
    echo '早上好';
}
else {
    echo '早安';
}
?>

地區語文清單的代碼係根據 ISO 3316 language code 。

  • 台灣地區之語文代碼為: zh-tw
  • 中國大陸地區之語文代碼為: zh-cn
  • 中文語文代碼為: zh

See also: PHP Manual:Predefined Variables

樂多舊網址: http://blog.roodo.com/rocksaying/archives/5540807.html

樂多舊回應
未留名 (#comment-15771167)
Fri, 15 Feb 2008 00:17:45 +0800
請問他是用 IP 來判斷使用者的嗎?
IP table 從哪邊來呢?
未留名 (#comment-15814629)
Wed, 20 Feb 2008 17:07:07 +0800
Accept-Language 的內容是使用者在瀏覽器中設定的。

Firefox 用戶可以在「工具/選項/進階」的「語言」中設定適用語文清單。

IE用戶是在「工具/網際網路選項/一般」的「語言」功能中設定。
未留名 (#comment-19885361)
Mon, 28 Sep 2009 21:04:29 +0800
請問GET /pub/WWW/ HTTP/1.1
Host: www.w3.org

這些東西是什麼的語言?php?還是???