Mobile_Detect 是一個輕量級 PHP 類,通過分析 User-Agent 識別移動設備、平板、具體作業系統、瀏覽器等。基於 MIT 協議開源,單文件即用。
// 方式1:直接下載 Mobile_Detect.php 放入項目
require_once 'Mobile_Detect.php';
// 方式2:Composer 安裝 (推薦)
composer require mobiledetect/mobiledetectlib
<?php
include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile()) {
// 任何移動平台(手機+平板)
echo 'isMobile';
// 進一步區分
if ($detect->isTablet()) {
echo ' - Tablet';
} else {
echo ' - Phone';
}
} else {
echo 'isPC';
}
// 更多檢測方法
$detect->isiOS(); // iOS 設備
$detect->isAndroidOS(); // Android 設備
$detect->is('iPhone'); // 特定機型
$detect->version('iPad'); // 獲取版本號
?>
// 獲取詳細信息
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
$os = $detect->is('iOS') ? 'iOS' : ($detect->is('AndroidOS') ? 'Android' : 'Other');
$browser = $detect->getBrowser(); // 需較新版本支持
// 針對特定設備組
if ($detect->is('UCBrowser') || $detect->is('QQBrowser')) {
// 國內常見瀏覽器特殊處理
}
// 緩存檢測結果(避免重複解析 UA)
$_SESSION['device_info'] = array(
'isMobile' => $detect->isMobile(),
'isTablet' => $detect->isTablet(),
'os' => $os,
'browser' => $browser
);
composer update)。