萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 瀏覽器偵測實作:基於 HTTP_USER_AGENT 的 IE/Gecko 版本判斷與現代替代方案

傳統 User Agent 解析函數

<?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; // 其他瀏覽器不支援
}
?>

關鍵邏輯說明

  • IE 判斷: 檢查 MSIE 關鍵字,排除 Mac IE 與 Opera 偽裝,擷取版本號 (如 MSIE 6.0 → 6.0)。
  • Gecko 判斷: 擷取 Gecko/YYYYMMDD 建置日期,以 2003/02/10 作為基準版本。
  • 回傳值: true 表示支援目標功能,false 表示不支援或無法辨識。

現代最佳實務:特性偵測優於瀏覽器偵測

User Agent 字串不可靠(可偽造、格式變動大),現代前端開發採用特性偵測:

JavaScript 端 (推薦)

// 原生特性偵測
if ('fetch' in window) { /* 支援 Fetch API */ }
if ('IntersectionObserver' in window) { /* 支援懶載入 */ }

// 條件式載入 Polyfill
if (!Element.prototype.closest) {
    // 載入 closest polyfill
}

PHP 端:僅作統計/日誌/相容性降級

<?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 提供降級方案,建議透過條件註釋 (`