CodeIgniter 使用手冊版本 2.1.4


User Agent 類別

提供函數來幫助你辨別瀏覽器資訊,例如:行動裝置或是機器人(Robot),此外你可以取得語系與編碼資訊

初始化類別

就像大多數在 CI 中的類別一樣,在控制器中初始化 User Agent 類別使用 $this->load->library 函數:

$this->load->library('user_agent');

載入後可以這樣使用: $this->agent

User Agent 定義

User Agent 的定義檔放置在 application/config/user_agents.php,如有必要你可以額外增加項目

範例

當 User Agent 初始化後,它將開始判斷是瀏覽器、行動裝置或機器人來造訪你的網頁,如果可以它也會取得平台資訊

$this->load->library('user_agent');

if ($this->agent->is_browser())
{
    $agent = $this->agent->browser().' '.$this->agent->version();
}
elseif ($this->agent->is_robot())
{
    $agent = $this->agent->robot();
}
elseif ($this->agent->is_mobile())
{
    $agent = $this->agent->mobile();
}
else
{
    $agent = 'Unidentified User Agent';
}

echo $agent;

echo $this->agent->platform(); // Platform info (Windows,Linux,Mac,etc.)

函數參考

$this->agent->is_browser()

判別是否為已知的瀏覽器,回傳 TRUE 或 FALSE

if ($this->agent->is_browser('Safari'))
{
    echo 'You are using Safari.';
}
else if ($this->agent->is_browser())
{
    echo 'You are using a browser.';
}

Note: 在這個範例中 "Safari" 這個字是你的瀏覽器清單中的一個陣列的索引值,你可以在 application/config/user_agents.php 找到瀏覽器清單

$this->agent->is_mobile()

判別是否為已知的行動裝置,回傳 TRUE 或 FALSE

if ($this->agent->is_mobile('iphone'))
{
    $this->load->view('iphone/home');
}
else if ($this->agent->is_mobile())
{
    $this->load->view('mobile/home');
}
else
{
    $this->load->view('web/home');
}

$this->agent->is_robot()

判別是否為已知的機器人,回傳 TRUE 或 FALSE

注意:  機器人清單中只包含了幾種最常見的機器人,你可以在 application/config/user_agents.php 新增新的機器人

$this->agent->is_referral()

判斷使用者是否從其它網站過來,回傳 TRUE 或 FALSE

$this->agent->browser()

回傳正在造訪你的網站的瀏覽器名稱

$this->agent->version()

回傳正在造訪你的網站的瀏覽器版本

$this->agent->mobile()

回傳正在造訪你的網站的行動裝置名稱

$this->agent->robot()

回傳正在造訪你的網站的機器人名稱

$this->agent->platform()

回傳正在造訪你的網站的平台名稱 (例如: Linux,Windows,OS X)

$this->agent->referrer()

假如使用者是從其它網站造訪,你可以取得 referrer 資訊:

if ($this->agent->is_referral())
{
    echo $this->agent->referrer();
}

$this->agent->agent_string()

取得完整的使用者代理(user agent)資訊,例如:

Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.4) Gecko/20060613 Camino/1.0.2

$this->agent->accept_lang()

如果使用者代理(user agent)接受特定語系,則你可以決定:

if ($this->agent->accept_lang('en'))
{
    echo 'You accept English!';
}

注意: 這個函數並不是那麼精確的,因為瀏覽器並不見得會提供有關語系的資訊

$this->agent->accept_charset()

如果使用者代理(user agent)接受特定編碼,則你可以決定:

if ($this->agent->accept_charset('utf-8'))
{
    echo 'You browser supports UTF-8!';
}

注意: 這個函數並不是那麼精確的,因為瀏覽器並不見得會提供有關編碼的資訊