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

PHP 判斷行動裝置存取的完整函式實作

     編輯:PHP 綜合知識

前言

在響應式設計普及前,伺服器端判斷行動裝置並提供專用版面是常見需求。本文提供一個經過實戰驗證的 isMobile() 函式,涵蓋四層檢測機制,可直接整合至專案中。

完整程式碼

<?php
/**
 * 判斷是否為行動裝置存取
 * @return bool
 */
function isMobile()
{
    // 1. 檢查 HTTP_X_WAP_PROFILE 標頭(WAP 裝置特徵)
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }

    // 2. 檢查 HTTP_VIA 標頭是否包含 wap(代理伺服器特徵)
    if (isset($_SERVER['HTTP_VIA'])) {
        return (bool) stripos($_SERVER['HTTP_VIA'], 'wap');
    }

    // 3. 依據 User-Agent 關鍵字比對(最常用、覆蓋率最高)
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientKeywords = [
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh',
            'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo',
            'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront',
            'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi',
            'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
        ];

        $pattern = '/' . implode('|', $clientKeywords) . '/i';
        if (preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }

    // 4. 協議檢查:Accept 標頭偏好 WML 而非 HTML(舊式功能機特徵)
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        $accept = $_SERVER['HTTP_ACCEPT'];
        $hasWml = stripos($accept, 'vnd.wap.wml') !== false;
        $hasHtml = stripos($accept, 'text/html') !== false;
        $wmlBeforeHtml = $hasWml && $hasHtml && (stripos($accept, 'vnd.wap.wml') < stripos($accept, 'text/html'));

        if ($hasWml && (!$hasHtml || $wmlBeforeHtml)) {
            return true;
        }
    }

    return false;
}
?>

四層檢測邏輯解析

  1. WAP Profile 標頭:最確定的行動裝置指標,優先級最高
  2. Via 代理標頭:部分行動網路代理會注入 wap 關鍵字
  3. User-Agent 比對:覆蓋主流品牌與瀏覽器核心,兼容性最廣
  4. Accept 協議偏好:作為最後防線,判斷舊裝置是否偏好 WML

使用範例

<?php
if (isMobile()) {
    // 載入行動版模板、重導至 m.example.com、簡化內容等
    include 'mobile/header.php';
} else {
    include 'desktop/header.php';
}
?>

現代替代方案提醒

雖然此函式實用,但現代開發建議採用:

  • 響應式設計 (RWD):CSS Media Queries + 彈性版面,單一代碼庫服務所有裝置
  • 前端特徵偵測:使用 navigator.userAgent 或 window.matchMedia 進行漸進式增強
  • 裝置偵測函式庫:如 DeviceDetector,準確度更高且持續更新

此函式適合:舊系統維護、快速原型、特定業務邏輯需區分裝置類型的場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved