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

PHP 行動裝置偵測庫 Mobile_Detect 完整應用指南

     編輯:PHP 相關知識

為何需要伺服器端偵測?

雖然響應式設計(RWD)是主流,但某些場景仍需伺服器端判斷裝置類型:

  • 針對行動裝置輕量化內容(減少圖片尺寸、移除複雜 JS)
  • 導向獨立行動版網址(如 m.example.com)
  • 依裝置載入不同 CSS/JS 套件
  • 分析流量來源、客製化行銷內容

Mobile_Detect 是輕量、無相依、持續更新的 PHP 庫,透過分析 User-Agent 標頭偵測裝置、作業系統、瀏覽器資訊。

安裝與基本用法

composer require mobiledetect/mobiledetectlib
<?php
require_once 'vendor/autoload.php'; // 或手動 include 'Mobile_Detect.php'
$detect = new Detection\MobileDetect;

// 基礎判斷
if ($detect->isMobile()) { /* 手機 */ }
if ($detect->isTablet()) { /* 平板 */ }
if ($detect->isMobile() && !$detect->isTablet()) { /* 手機非平板 */ }

// 作業系統判斷
if ($detect->isiOS()) { /* iOS */ }
if ($detect->isAndroidOS()) { /* Android */ }
if ($detect->isWindowsPhoneOS()) { /* Windows Phone */ }

// 具體裝置
if ($detect->is('iPhone')) { /* iPhone */ }
if ($detect->is('iPad')) { /* iPad */ }
if ($detect->is('Samsung')) { /* 三星裝置 */ }

應用場景一:導向行動版網站

<?php
$detect = new Detection\MobileDetect;
if ($detect->isMobile()) {
    header('Location: https://m.example.com/');
    exit;
}
?>

建議放在入口檔案(如 index.php)最頂端,避免輸出任何內容前重導向。

應用場景二:依裝置載入不同資源

<?php
$detect = new Detection\MobileDetect;
if ($detect->isMobile() || $detect->isTablet()) {
    echo '<link rel="stylesheet" href="mobile.css">';
} else {
    echo '<link rel="stylesheet" href="desktop.css">';
}
?>

進階功能

  • 版本偵測:$detect->version('iOS') 返回版本號(如 14.5)。
  • 自訂 User-Agent 測試:$detect->setUserAgent('custom UA string') 方便單元測試。
  • 快取機制:庫內部快取匹配結果,同一請求多次呼叫無效能負擔。

重要提醒

Mobile_Detect 僅是伺服器端輔助工具,不能取代響應式設計或客戶端功能偵測(如 Modernizr)。 請定期 composer update 以獲取最新裝置規則,確保偵測準確度。

替代方案

  • PHP User Agent Parser(更詳細的瀏覽器/引擎解析)
  • Nginx/Apache 模組(如 ngx_http_user_agent_module)在 Web 伺服器層偵測並設定變數
  • Client Hints(新標準,瀏覽器主動發送裝置資訊)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved