在響應式設計普及前,伺服器端判斷行動裝置並提供專用版面是常見需求。本文提供一個經過實戰驗證的 isMobile() 函式,涵蓋四層檢測機制,可直接整合至專案中。
<?php
/**
* 判斷是否為行動裝置存取
* @return bool
*/
function isMobile()
{
// 1. 檢查 HTTP_X_WAP_PROFILE 標頭(WAP 裝置特徵)
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
// 2. 檢查 HTTP_VIA 標頭是否包含 wap(代理伺服器特徵)
if (isset($_SERVER['HTTP_VIA'])) {
return (bool) stripos($_SERVER['HTTP_VIA'], 'wap');
}
// 3. 依據 User-Agent 關鍵字比對(最常用、覆蓋率最高)
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$clientKeywords = [
'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh',
'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo',
'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront',
'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi',
'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
];
$pattern = '/' . implode('|', $clientKeywords) . '/i';
if (preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']))) {
return true;
}
}
// 4. 協議檢查:Accept 標頭偏好 WML 而非 HTML(舊式功能機特徵)
if (isset($_SERVER['HTTP_ACCEPT'])) {
$accept = $_SERVER['HTTP_ACCEPT'];
$hasWml = stripos($accept, 'vnd.wap.wml') !== false;
$hasHtml = stripos($accept, 'text/html') !== false;
$wmlBeforeHtml = $hasWml && $hasHtml && (stripos($accept, 'vnd.wap.wml') < stripos($accept, 'text/html'));
if ($hasWml && (!$hasHtml || $wmlBeforeHtml)) {
return true;
}
}
return false;
}
?>
wap 關鍵字<?php
if (isMobile()) {
// 載入行動版模板、重導至 m.example.com、簡化內容等
include 'mobile/header.php';
} else {
include 'desktop/header.php';
}
?>
雖然此函式實用,但現代開發建議採用:
navigator.userAgent 或 window.matchMedia 進行漸進式增強此函式適合:舊系統維護、快速原型、特定業務邏輯需區分裝置類型的場景。