解析 $_SERVER['HTTP_USER_AGENT'] 字串,關鍵字匹配:
<?php
function detectDevice(): array
{
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
return [
'is_pc' => strpos($ua, 'windows nt') !== false,
'is_iphone' => strpos($ua, 'iphone') !== false,
'is_ipad' => strpos($ua, 'ipad') !== false,
'is_android' => strpos($ua, 'android') !== false,
];
}
// 使用範例
$device = detectDevice();
if ($device['is_pc']) echo 'PC';
if ($device['is_iphone']) echo 'iPhone';
if ($device['is_ipad']) echo 'iPad';
if ($device['is_android']) echo 'Android';
?>
<?php
function getDeviceType(): string
{
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
if (strpos($ua, 'iphone') !== false || strpos($ua, 'ipad') !== false) return 'ios';
if (strpos($ua, 'android') !== false) return 'android';
return 'other';
}
?>
android,若需區分手機/平板,需進一步檢查 mobile 關鍵字或螢幕尺寸(需 JS 協助)。bot、crawler、spider 等關鍵字,歸類為 bot。strpos 極快,可直接在每請求執行,無需快取。Sec-CH-UA-Mobile、Sec-CH-UA-Platform 等標準標頭,比 UA 更結構化、隱私友善。composer require mobiledetect/mobiledetectlib,提供豐富 isMobile()、isTablet()、isiOS() 等方法。簡單專案用 strpos 關鍵字匹配即可滿足 90% 需求;追求準確度、可維護性,請引入成熟函式庫或採用 Client Hints。記住:UA 僅供體驗優化,不可信任。