PHP Mobile Device Detection,簡單地用 PHP 判斷訪客的上網裝置

Alex Liu
25sprout
Published in
4 min readAug 29, 2012

--

行動裝置如手機、平板已快速的取代傳統電腦成為許多網友上網的主要裝置之一。

目前最主流的行動裝置作業系統為 iOS & Android,所使用的瀏覽器分別為:safari & chrome。對於一個 web開發人員來說,有時候會需要針對不同的裝置或 OS 進行調整。最明顯的例子如因為 iOS 不支援 Flash,所以假設某個網站設計了一個 Flash 動畫歡迎頁,那當訪客持 iPad or iPhone 進入首頁時只會看到一片空白。因此需要在進入網站前就先判斷訪客的上網裝置,若是使用 iOS 的時候則直接跳過 Flash 歡迎頁進到真正的網站(用 html 建置的網站)。

我們在網路搜尋了許久發現了一個寫得非常漂亮且運作良好的 PHP行動裝置偵測程式(PHP Mobile Device Detection),只要直接將下面的語言複製貼上到您要建立判斷的網頁即可。

//Detect special conditions devices
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
if(stripos($_SERVER['HTTP_USER_AGENT'],"Android") && stripos($_SERVER['HTTP_USER_AGENT'],"mobile")){
$Android = true;
}else if(stripos($_SERVER['HTTP_USER_AGENT'],"Android")){
$Android = false;
$AndroidTablet = true;
}else{
$Android = false;
$AndroidTablet = false;
}
$webOS = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");
$BlackBerry = stripos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$RimTablet= stripos($_SERVER['HTTP_USER_AGENT'],"RIM Tablet");
//do something with this information
if( $iPod || $iPhone ){
//were an iPhone/iPod touch -- do something here
}else if($iPad){
//were an iPad -- do something here
}else if($Android){
//we're an Android Phone -- do something here
}else if($AndroidTablet){
//we're an Android Phone -- do something here
}else if($webOS){
//we're a webOS device -- do something here
}else if($BlackBerry){
//we're a BlackBerry phone -- do something here
}else if($RimTablet){
//we're a RIM/BlackBerry Tablet -- do something here
}else{
//we're not a mobile device.
}
就這麼簡單 Enjoy it!原文出處:http://www.schiffner.com/programming-php-classes/php-mobile-device-detection/(Photo Via Nick Kuijpers, CC License)

--

--

25sprout 共同創辦人暨 CEO。熱愛旅行和美食,是一個很能走的背包客和願意排隊的美食探索者。