透過分析 `$_SERVER['HTTP_USER_AGENT']` 字串,可識別用戶裝置作業系統(iOS/Android)及是否為微信內建瀏覽器。本文提供三種判斷寫法與微信檢測範例,並說明注意事項。
User-Agent 範例:
Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1
Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Mobile Safari/537.36
... MicroMessenger/8.0.16 ... (微信)
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';
}
// 使用
$type = getDeviceType(); // 'ios' | 'android' | 'other'
echo "Device: $type";
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (stripos($ua, 'iPhone') || stripos($ua, 'iPad')) {
echo 'iOS';
} elseif (stripos($ua, 'Android')) {
echo 'Android';
} else {
echo 'Other';
}
function detectOS(string $ua): string {
$patterns = [
'ios' => '/iphone|ipad|ipod/i',
'android' => '/android/i',
'windows' => '/windows phone/i',
'mac' => '/macintosh|mac os x/i',
];
foreach ($patterns as $os => $regex) {
if (preg_match($regex, $ua)) return $os;
}
return 'unknown';
}
function isWeChat(): bool {
return strpos($_SERVER['HTTP_USER_AGENT'] ?? '', 'MicroMessenger') !== false;
}
function getWeChatVersion(): ?string {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/MicroMessenger\/([\d.]+)/', $ua, $m)) {
return $m[1]; // 如 '8.0.16'
}
return null;
}
// 業務邏輯範例
if (!isWeChat()) {
header('HTTP/1.1 403 Forbidden');
exit('請在微信中打開');
}
echo "微信版本: " . getWeChatVersion();
善用 UA 解析庫(如 `jenssegers/agent`)可獲得更完整的裝置、瀏覽器、機器人資訊,適合分析統計與複雜業務分流。