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

PHP 識別移動端訪問的完整方案:User-Agent、HTTP_ACCEPT 與 JS 重定向

     編輯:PHP 相關知識

方案一:User-Agent 關鍵字匹配 (最常用)

function isMobileUA() {
    $ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    $mobileKeywords = [
        'mobile', 'android', 'iphone', 'ipad', 'ipod',
        'blackberry', 'windows phone', 'opera mini', 'opera mobi',
        'ucweb', 'ucbrowser', 'micromessenger', 'qq/', 'wechat',
        'netfront', 'symbian', 'series60', 'series40', 'midp',
        'cldc', 'wap', 'nokia', 'sony', 'ericsson', 'mot-',
        'samsung', 'htc', 'lg-', 'sharp', 'sie-', 'philips',
        'panasonic', 'alcatel', 'lenovo', 'huawei', 'xiaomi',
        'meizu', 'vivo', 'oppo', 'oneplus', 'googlebot-mobile'
    ];
    foreach ($mobileKeywords as $kw) {
        if (strpos($ua, $kw) !== false) return true;
    }
    return false;
}

方案二:HTTP_ACCEPT 協議檢測 (輔助)

function isMobileAccept() {
    if (empty($_SERVER['HTTP_ACCEPT'])) return false;
    $accept = strtolower($_SERVER['HTTP_ACCEPT']);
    // 明確支援 WML 且不支援 HTML,或 WML 優先級高於 HTML
    $hasWml = strpos($accept, 'vnd.wap.wml') !== false;
    $hasHtml = strpos($accept, 'text/html') !== false;
    if ($hasWml && (!$hasHtml || strpos($accept, 'vnd.wap.wml') < strpos($accept, 'text/html'))) {
        return true;
    }
    return false;
}

方案三:綜合判斷函數 (推薦生產使用)

function isMobile() {
    // 1. 快速特徵頭
    if (!empty($_SERVER['HTTP_X_WAP_PROFILE']) || !empty($_SERVER['HTTP_PROFILE'])) return true;
    if (isset($_SERVER['HTTP_VIA']) && stripos($_SERVER['HTTP_VIA'], 'wap') !== false) return true;

    // 2. User-Agent 深度檢測
    if (isMobileUA()) return true;

    // 3. Accept 協議輔助
    if (isMobileAccept()) return true;

    return false;
}

// 使用:自動跳轉
if (isMobile()) {
    header('Location: https://m.example.com' . $_SERVER['REQUEST_URI'], true, 302);
    exit;
}

方案四:JavaScript 客戶端重定向 (靜態頁/無 PHP 環境)

<script>
(function() {
    var ua = navigator.userAgent.toLowerCase();
    var isMobile = /ipad|iphone|ipod|android|mobile|windows phone|blackberry|ucweb|micromessenger|qq\//.test(ua);
    var target = isMobile ? 'https://m.example.com' : 'https://www.example.com';
    // 避免重定向循環
    if (location.hostname !== new URL(target).hostname) {
        location.href = target + location.pathname + location.search;
    }
})();
</script>

響應式設計時代的建議

  • 優先響應式 CSS (Media Queries): 一套代碼適配所有屏幕,無需跳轉,利於 SEO。
  • 動態服務 (RESS): 服務端識別設備類型,輸出不同 HTML 結構 (如簡化導航、縮圖),但 URL 保持一致。
  • 避免單純 UA 跳轉: 維護成本高、易誤判、影響緩存、SEO 風險 (Google 建議同一 URL)。
  • 必要時跳轉: 只有極大差異 (如舊版 WAP、獨立 App 下載頁) 才考慮 302 重定向,並提供「切換至桌面版」鏈接 (設置 Cookie 記住選擇)。

常見誤區

  1. 以為 iPad 是移動端 —— 現代 iPadOS 桌面級瀏覽器,通常應歸類為桌面端。
  2. 只檢測 android —— 遺漏了大量國產定制 ROM、車載系統、智能電視。
  3. 不更新關鍵字庫 —— 新機型、新瀏覽器 (如 HarmonyOS, MiuiBrowser) 持續出現。
  4. 忽略 tablet 分類 —— 平板介於手機與桌面之間,UI 適配策略不同。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved