利用 $_SERVER['HTTP_USER_AGENT'] 檢測瀏覽器標識,在舊版 Internet Explorer (含 IE11) 中顯示特定廣告或內容。注意:現代 Edge (Chromium 核心) UA 不含 "MSIE",若需包含 Edge Legacy 需額外判斷。
<? if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false): ?>
<!-- 此處放置廣告代碼 (Google AdSense、聯盟碼、圖片等) -->
<div class="ie-only-ad">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-XXXX" data-ad-slot="YYYY" data-ad-format="auto"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
</div>
<? endif; ?>
<?php if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false): ?>
<!-- 廣告代碼 -->
<?php endif; ?>
IE 11 的 UA 字串不再包含 "MSIE",改含 "Trident/7.0; rv:11.0"。若需涵蓋所有 IE:
<?php
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$isIE = (strpos($ua, 'MSIE') !== false) || (strpos($ua, 'Trident/') !== false && strpos($ua, 'rv:') !== false);
// 或使用正則
// $isIE = (bool)preg_match('/(MSIE|Trident\/.*rv:)/', $ua);
if ($isIE): ?>
<!-- IE 專屬內容 -->
<?php endif; ?>
| 瀏覽器 | User-Agent 片段 | MSIE | Trident/rv: |
|---|---|---|---|
| IE 8-10 | Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0) | ✅ | ✅ |
| IE 11 | Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko | ❌ | ✅ |
| Edge Legacy (EdgeHTML) | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363 | ❌ | ❌ |
| Edge Chromium | Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0 | ❌ | ❌ |
| Chrome/Firefox/Safari | ... 無 MSIE 或 Trident ... | ❌ | ❌ |
@supports、條件註解 (僅 IE 支援)、Polyfill (core-js)if ('feature' in window) 特性偵測替代瀏覽器偵測