<?php
function detectBrowser(): bool {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
// IE (非 Mac、非 Opera 偽裝)
if (stripos($ua, 'MSIE') !== false
&& stripos($ua, 'mac') === false
&& stripos($ua, 'Opera') === false) {
$version = (float)substr($ua, stripos($ua, 'MSIE') + 5, 3);
return $version >= 5.5; // IE 5.5+
}
// Gecko 引擎 (Firefox、Mozilla 等)
if (stripos($ua, 'Gecko/') !== false) {
$buildDate = (int)substr($ua, stripos($ua, 'Gecko/') + 6, 8); // YYYYMMDD
return $buildDate >= 20030210; // Gecko 2003/02/10 以降
}
return false; // 其他瀏覽器不支援
}
?>
MSIE 關鍵字,排除 Mac IE 與 Opera 偽裝,擷取版本號 (如 MSIE 6.0 → 6.0)。Gecko/YYYYMMDD 建置日期,以 2003/02/10 作為基準版本。true 表示支援目標功能,false 表示不支援或無法辨識。User Agent 字串不可靠(可偽造、格式變動大),現代前端開發採用特性偵測:
// 原生特性偵測
if ('fetch' in window) { /* 支援 Fetch API */ }
if ('IntersectionObserver' in window) { /* 支援懶載入 */ }
// 條件式載入 Polyfill
if (!Element.prototype.closest) {
// 載入 closest polyfill
}
<?php
// 僅用於記錄瀏覽器分佈,不作功能開關
function logBrowserInfo(): array {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
// 可整合 ua-parser/browscap 等資料庫解析詳細資訊
return [
'ua' => $ua,
'is_mobile' => stripos($ua, 'Mobile') !== false,
'is_bot' => (bool)preg_match('/bot|crawler|spider/i', $ua),
];
}
?>
伺服器端避免以 User Agent 決定業務邏輯分支。前端採用漸進式增強與特性偵測,PHP 僅記錄 UA 供分析用途。若必須針對舊版 IE 提供降級方案,建議透過條件註釋 (`