588创业论坛
标题:
php判断页面是移动端访问还是pc端访问的代码
[打印本页]
作者:
匿名
时间:
2020-2-2 16:05
标题:
php判断页面是移动端访问还是pc端访问的代码
在使用浏览器发起的 HTTP 请求中,通常会包含一个识别标识。它名为 User Agent,简称 UA。它是一串包含了客户端基础信息的字符串。因此可以通过它可以方便的获取客户端的操作系统,语言,浏览器和版本信息。
1、PHP获取UA标识
获取代码:
echo $_SERVER['HTTP_USER_AGENT'];
复制代码
运行结果:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
复制代码
2、创建一个可以根据得到的字符串匹配出访问方式的PHP函数,整个PHP判断代码如下:
$user_agent = $_SERVER['HTTP_USER_AGENT'];
function isMobile($ua)
{
//目前手机系统很多种,为了尽量准确,所以建立一个手机系统关键词的数组。
$mobile_agents = array ('iphone','android','phone','mobile','wap','netfront','java','opera mobi',
'opera mini','ucweb','windows ce','symbian','series','webos','sony','blackberry','dopod',
'nokia','samsung','palmsource','xda','pieplus','meizu','midp','cldc','motorola','foma',
'docomo','up.browser','up.link','blazer','helio','hosin','huawei','novarra','coolpad',
'techfaith','alcatel','amoi','ktouch','nexian','ericsson','philips','sagem','wellcom',
'bunjalloo','maui','smartphone','iemobile','spice','bird','zte-','longcos','pantech',
'gionee','portalmmm','jig browser','hiptop','benq','haier','^lct','320x320','240x320',
'176x220','windows phone','cect','compal','ctl','lg','nec','tcl','daxian','dbtel','eastcom',
'konka','kejian','lenovo','mot','soutec','sgh','sed','capitel','panasonic','sonyericsson',
'sharp','panda','zte','acer','acoon','acs-','abacho','ahong','airness','anywhereyougo.com',
'applewebkit/525','applewebkit/532','asus','audio','au-mic','avantogo','becker','bilbo',
'bleu','cdm-','danger','elaine','eric','etouch','fly ','fly_','fly-','go.web','goodaccess',
'gradiente','grundig','hedy','hitachi','htc','hutchison','inno','ipad','ipaq','ipod',
'jbrowser','kddi','kgt','kwc','lg ','lg2','lg3','lg4','lg5','lg7','lg8','lg9','lg-','lge-',
'lge9','maemo','mercator','meridian','micromax','mini','mitsu','mmm','mmp','mobi','mot-',
'moto','nec-','newgen','nf-browser','nintendo','nitro','nook','obigo','palm','pg-',
'playstation','pocket','pt-','qc-','qtek','rover','sama','samu','sanyo','sch-','scooter',
'sec-','sendo','sgh-','siemens','sie-','softbank','sprint','spv','tablet','talkabout',
'tcl-','teleca','telit','tianyu','tim-','toshiba','tsm','utec','utstar','verykool','virgin',
'vk-','voda','voxtel','vx','wellco','wig browser','wii','wireless','xde','pad','gt-p1000');
$ismobile = false;
foreach ($mobile_agents as $device) {
if (stristr($ua, $device)) {
$ismobile = true;
break;
}
}
return $ismobile;
}
if(isMobile($user_agent)){
echo "在移动端访问";
}else{
echo "在电脑端访问";
}
复制代码
作者:
匿名
时间:
2020-2-2 16:09
代码来源于《进阶丶之路》博客,感谢分享!为了容易理解,稍微修改增加了一些!
欢迎光临 588创业论坛 (http://bbs.588cy.com/)
Powered by Discuz! X2.5