分享

移动设备(手机平板等)检测的 PHP 类库Mobile Detect

今天写了个项目要分别部署pc版和手机版,不同域名(不同入口)找了很久,找到这个类库,算是对设备识别较好的类库了,比起做js之类的我觉得直接写入php入口文件会比较好些,唯一的缺点就是没有对url自动匹配跳转,所以还是歹花时间研究一番。

git项目地址:https://github.com/serbanghita/Mobile-Detect

Mobile_Detect 使用实例

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
 
// Check for any mobile device.
if ($detect->isMobile())
 
// Check for any tablet.
if($detect->isTablet())
 
// Check for any mobile device, excluding tablets.
if ($detect->isMobile() && !$detect->isTablet())
 
if ($detect->isMobile() && !$detect->isTablet())
 
// Alternative to $detect->isAndroidOS()
$detect->is('AndroidOS');
 
// Batch usage
foreach($userAgents as $userAgent){
  $detect->setUserAgent($userAgent);
  $isMobile = $detect->isMobile();
}
 
// Version check.
$detect->version('iPad'); // 4.3 (float)

 

thinkphp框架可以在入口文件处做识别

require_once './lib/Mobile_Detect.php';
$detect = new Mobile_Detect;
 
if ($detect->isMobile()){
	header("location:http://m.xxx.cn"); 移动设备访问跳转到此域名
}else {
 
 
//PC访问
// 应用入口文件
 
// 检测PHP环境
if(version_compare(PHP_VERSION,'5.3.0','<')) die('require PHP > 5.3.0 !');
 
// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);
 
 
// 定义应用目录
define('APP_PATH','./Application/');
// 引入ThinkPHP入口文件
require './ThinkPHP/ThinkPHP.php';
 
// 亲^_^ 后面不需要任何代码了 就是如此简单
 
}

 

留言