雖然響應式設計(RWD)是主流,但某些場景仍需伺服器端判斷裝置類型:
m.example.com)Mobile_Detect 是輕量、無相依、持續更新的 PHP 庫,透過分析 User-Agent 標頭偵測裝置、作業系統、瀏覽器資訊。
composer require mobiledetect/mobiledetectlib
<?php
require_once 'vendor/autoload.php'; // 或手動 include 'Mobile_Detect.php'
$detect = new Detection\MobileDetect;
// 基礎判斷
if ($detect->isMobile()) { /* 手機 */ }
if ($detect->isTablet()) { /* 平板 */ }
if ($detect->isMobile() && !$detect->isTablet()) { /* 手機非平板 */ }
// 作業系統判斷
if ($detect->isiOS()) { /* iOS */ }
if ($detect->isAndroidOS()) { /* Android */ }
if ($detect->isWindowsPhoneOS()) { /* Windows Phone */ }
// 具體裝置
if ($detect->is('iPhone')) { /* iPhone */ }
if ($detect->is('iPad')) { /* iPad */ }
if ($detect->is('Samsung')) { /* 三星裝置 */ }
<?php
$detect = new Detection\MobileDetect;
if ($detect->isMobile()) {
header('Location: https://m.example.com/');
exit;
}
?>
建議放在入口檔案(如 index.php)最頂端,避免輸出任何內容前重導向。
<?php
$detect = new Detection\MobileDetect;
if ($detect->isMobile() || $detect->isTablet()) {
echo '<link rel="stylesheet" href="mobile.css">';
} else {
echo '<link rel="stylesheet" href="desktop.css">';
}
?>
$detect->version('iOS') 返回版本號(如 14.5)。$detect->setUserAgent('custom UA string') 方便單元測試。Mobile_Detect 僅是伺服器端輔助工具,不能取代響應式設計或客戶端功能偵測(如 Modernizr)。 請定期
composer update以獲取最新裝置規則,確保偵測準確度。
ngx_http_user_agent_module)在 Web 伺服器層偵測並設定變數