透過 `$_SERVER['HTTP_USER_AGENT']` 判斷裝置類型,進行行動版/桌面版分流是早期常見做法。現代開發**強烈建議採用響應式設計 (RWD) + CSS Media Queries**,單一 URL 服務所有裝置,利於 SEO、快取、分享。本文提供 UA 解析實作供維舊專案參考,並說明遷移策略。
<?php
/**
* 判斷是否為行動裝置
* @return bool true=行動裝置, false=桌面/其他
*/
function isMobile(): bool {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (!$ua) return false;
// 註解區塊 (如 Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) ...)
$commentBlock = '';
if (preg_match('/\(.*?\)/', $ua, $m)) $commentBlock = $m[0];
// 作業系統關鍵字
$osKeywords = [
'Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian',
'Android', 'armv6l', 'armv5', 'Mobile', 'CentOS', 'mowser',
'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web',
'Palm', 'iPAQ',
];
// 裝置/瀏覽器 Token
$tokenKeywords = [
'Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220',
'240×240', '240×320', '320×240', 'UP.Browser', 'UP.Link',
'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia',
'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision', 'Iris',
'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo',
'iPhone', 'iPod', 'iPad', 'Android', 'Mobile', 'Silk', 'Kindle',
];
$check = function (array $keywords, string $text): bool {
foreach ($keywords as $kw) {
if (stripos($text, $kw) !== false) return true;
}
return false;
};
return $check($osKeywords, $commentBlock) || $check($tokenKeywords, $ua);
}
// 使用範例:重導向
if (isMobile()) {
header('Location: https://m.example.com' . $_SERVER['REQUEST_URI']);
} else {
header('Location: https://www.example.com' . $_SERVER['REQUEST_URI']);
}
exit;
?>
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 響應式設計 (RWD) | 單一 URL、SEO 友好、維護單一代碼庫、無重導向延遲 | 複雜佈局 CSS 較重、圖片需響應式處理 | **所有新專案首選** |
| 動態服務 (同一 URL, 不同 HTML) | URL 不變、可針對裝置輸出精簡 HTML | 需 Vary: User-Agent 標頭、快取複雜、Google 建議配合 RWD | 極度差異的行動/桌面體驗 |
| 獨立子域名 (m.example.com) | 行動版極致優化、技術棧可分離 | 雙維護成本、SEO 需 `rel=alternate/canonical`、重導向失敗風險 | 舊專案、極特殊需求 |
| PHP UA 重導向 | 實作簡單、無需前端配合 | UA 易偽造/遺漏、維護關鍵字庫、重導向影響速度與 SEO | **不建議新專案使用** |
手寫關鍵字庫極難維護,建議用 Composer 引入:
composer require mobiledetect/mobiledetectlib
<?php
require 'vendor/autoload.php';
$detect = new Detection\MobileDetect();
if ($detect->isMobile()) { /* ... */ }
if ($detect->isTablet()) { /* ... */ }
if ($detect->isiOS()) { /* ... */ }
$detect->getUserAgent(); // 取得解析詳情
?>
更多響應式設計最佳實踐、CSS Container Queries、行動優先斷點策略、圖片最佳化 (WebP, AVIF, 延遲載入)、PWA 漸進式網頁應用、Core Web Vitals 優化、Server-Side Rendering (SSR) 與裝置適配、A/B 測試行動版體驗,請參考本站專題系列。