首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 僅在 IE 瀏覽器顯示內容:User-Agent 判斷與現代替代方案

     編輯:PHP 相關知識

經典做法(短標籤版)

<? if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false): ?>
    <!-- 這裡放廣告碼、IE 專用 CSS/JS、Polyfill 等 -->
    <script src="/assets/js/ie-polyfills.js"></script>
<? endif; ?>

標準 PHP 標籤版(推薦,不依賴 short_open_tag)

<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false): ?>
    <!-- IE 專用內容 -->
<?php endif; ?>

⚠️ 關鍵限制與現狀

重要提醒:
  • IE 已於 2022 年 6 月 15 日正式停止支援(Windows 10 半年度通道),Edge 已全面取代。
  • MSIE 關鍵字僅存在於 IE 10 及更舊版本。IE 11 的 UA 字串為 Trident/7.0; rv:11.0,**不含 MSIE**。
  • Edge (Chromium) UA **不含 MSIE/Trident**,無法被此判斷捕獲。
  • 現代網站**極少需要**針對 IE 撰寫特殊邏輯,建議採用漸進增強與特性偵測。

完整版瀏覽器判斷函式(含 IE 11、Edge Legacy)

<?php
/**
 * 偵測 IE / Edge Legacy
 * @return array ['is_ie'=>bool, 'version'=>int|null, 'engine'=>string]
 */
function detectIE(): array
{
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // IE 10 及更舊
    if (preg_match('/MSIE\s([0-9.]+)/', $ua, $m)) {
        return ['is_ie' => true, 'version' => (int)$m[1], 'engine' => 'MSIE'];
    }
    
    // IE 11
    if (strpos($ua, 'Trident/') !== false && preg_match('/rv:(\d+)/', $ua, $m)) {
        return ['is_ie' => true, 'version' => (int)$m[1], 'engine' => 'Trident'];
    }
    
    // Edge Legacy (EdgeHTML)
    if (preg_match('/Edge\/(\d+)/', $ua, $m)) {
        return ['is_ie' => false, 'version' => (int)$m[1], 'engine' => 'EdgeHTML'];
    }
    
    return ['is_ie' => false, 'version' => null, 'engine' => 'Other'];
}

// 使用
$browser = detectIE();
if ($browser['is_ie']) {
    echo "<!-- IE {$browser['version']} 專用內容 -->";
}

現代最佳實踐:特性偵測取代瀏覽器偵測

**伺服器端 UA 判斷本質脆弱**(UA 可偽造、瀏覽器更新快、維護成本高)。前端採用以下方案:

1. CSS @supports / 媒體查詢

<!-- 現代瀏覽器載入現代樣式 -->
<link rel="stylesheet" href="/css/modern.css" media="not all and (pointer: coarse)">

<!-- 舊版 IE 載入 fallback(IE 不支援 media query 的某些語法) -->
<!--[if IE]>
    <link rel="stylesheet" href="/css/ie-fallback.css">
<![endif]-->

2. JavaScript 特性偵測

<script>
// 檢測功能而非瀏覽器
if (!Element.prototype.closest) {
    // 載入 Polyfill
    document.write('<script src="/polyfills/closest.js"><\/script>');
}

// 或使用現代模組化載入
import('/polyfills/fetch.js').then(() => {
    // fetch 可用
});

3. Polyfill.io 服務(自動依 UA 回傳所需 Polyfill)

<script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,Promise,Object.assign"></script>

4. 條件式註解(僅 IE 10 及舊版支援)

<!--[if IE]>
    <p>您正在使用已淘汰的 Internet Explorer,請升級至 Edge、Chrome 或 Firefox。</p>
<![endif]-->

總結

  • 伺服器端 `strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')` 僅能偵測 **IE 10 及更舊版本**。
  • IE 11 需檢查 `Trident` + `rv:`;Edge Legacy 需檢查 `Edge/`。
  • 2024 年後,生產環境強烈不建議維護 IE 相容程式碼,資源應投入現代標準與漸進增強。
  • 若因企業內部系統被迫支援 IE,請隔離在獨立模組,並設定明確淘汰時間表。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved