使用Mobile Detect套件檢測行動裝置

Mobile Detect
Mobile Detect 是一個檢測行動裝置的輕量級php套件,我們可以利用它來達成RESS(響應式設計+伺服器端組件)。
一般我們在設計響應式網站時,大多是載入相同的內容,再依螢幕寬度決定顯示或隱藏哪些網頁元素,以及網頁元素的排列方式。但是這種作法對性能較差的手執裝置來說,是一種相當耗資源的方式,如果可以依裝置載入相對應的內容,當然是一種比較聰明的方法囉。
這裡我們列舉了使用的方法,歡迎取用唷!
// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
// 所有行動裝置 (手機+平板).
if ( $detect->isMobile() ) {
}
// 只有平版
if( $detect->isTablet() ){
}
//只有手機
if( $detect->isMobile() && !$detect->isTablet() ){
}
// 檢查平台
//iOS系統
if( $detect->isiOS() ){
}
// Android系統
if( $detect->isAndroidOS() ){
}
// 檢查特定的屬性
// 這方法還在測試中、之後可能會有所調整
$detect->is('Chrome') //判斷是Chrome瀏覽器
$detect->is('UC Browser') //判斷是UC Browser
// [...]
// Batch mode using setUserAgent():
$userAgents = array(
'Mozilla/5.0 (Linux; Android 4.0.4; Desire HD Build/IMM76D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19',
'BlackBerry7100i/4.1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/103',
// [...]
);
foreach($userAgents as $userAgent){
$detect->setUserAgent($userAgent);
$isMobile = $detect->isMobile();
$isTablet = $detect->isTablet();
// Use the force however you want.
}
// Get the version() of components.
// WARNING: this method is in BETA, some keyword properties will change in the future.
$detect->version('iPad'); // 4.3 (float)
$detect->version('iPhone') // 3.1 (float)
$detect->version('Android'); // 2.1 (float)
$detect->version('Opera Mini'); // 5.0 (float)
// [...]
我要留言