当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP检测移动设备类mobile detection使用实例

PHP检测移动设备类mobile detection使用实例

2019年03月27日  | 移动技术网IT编程  | 我要评论

目前,一个网站有多个版本是很正常的,如pc版,3g版,移动版等等。根据不同的浏览设备我们需要定向到不同的版本中。不仅如此,我们有时候还需要根据不同的客户端加载不同的css,因此我们需要能够检测浏览设备,so,我们就需要用到“mobile detection”类库。

“mobile detection”是一个轻量级移动设备检测的php类库,它采用结合特定的http标头中的user-agent字符串来检测移动客户端环境。注意,mobile detection 只是一个服务器端(php)的检测工具,并不能代替响应式web设计或其他任何形式的客户端功能检测。

mobile detection 类库下载地址:https://github.com/serbanghita/mobile-detect

实例1:根据设备重定向到其他版本

当我们使用移动设备浏览某网站时,需要定向到该网站的移动版,首先将具有检测功能的文件mobile_detect.php包含到网页中或主页中,现在我们来实现浏览www.uncletoo.com网站时重定向到m.uncletoo.com中:

复制代码 代码如下:

/*根据文件位置更改路径信息*/
require_once 'mobile_detect.php';
$detect = new mobile_detect;
if($detect->ismobile()) {
    header('location: http://m.uncletoo.com/');
    exit;
}
这是定向到移动网站,下面还有其他形式的重定向:
//所有平板设备
if( $detect->istablet()) {
}
//是移动但非平板设备
if( $detect->ismobile() && !$detect->istablet()) {
}
//ios系统
if( $detect->isios()) {
}
//android系统
if( $detect->isandroidos()) {
}
//windowsphone系统
if( $detect->iswindowsphoneos()) {
}

实例2:根据不同设备加载不同资源

如上所述,我们还可以根据不同的浏览设备加载不同的css文件。如:

复制代码 代码如下:

$detect = new mobile_detect;
if($detect->ismobile() || $detect->istablet()) {
    echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
    echo "<link rel='stylesheet' href='style.css type='text/css' />";
}

注意,mobile detection是一个移动设备检测平台,随着科技的进步会有不同的设备出现,因此你需要随时更新类库,这样才能保证检测的准确性。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网