乌徒帮技术范WEB开发PHP › php判断是否为手机浏览器的函数

php判断是否为手机浏览器的函数

分类:PHP

乌徒帮发布的wordpress手机版和wordpress主程序相互呼应,不过否子戈想实现当用户用手机访问主站的时候出现进入手机版的提示,虽然可以通过CSS或javascript来实现,然而经过尝试,都不完美。为此,我专门查阅了一些资料,自己建立了一个php判断是否为手机浏览器的函数,用来实现上述目标。

我们通过对浏览器的USER_AGENT来判断用户是否在使用手机浏览器。USER_AGENT是php用来接收用户访问设备的参数,通过用户访问网站时传送的数据实现。在php用,用echo $_SERVER['HTTP_USER_AGENT']来打印和查看用户的设备(设备使用者才能看到)。而对于程序猿,则利用这个数据判断来访用户所使用的浏览器信息。我们建立以下的php函数:

function is_mobile(){
?? ?$user_agent = $_SERVER['HTTP_USER_AGENT'];
?? ?if(trim($user_agent) == '')return true;//如果客户端信息为空,我们也认为该设备为手机设备
?? ?$mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte",'Opera Mini','Kindle','Silk/','Mobile','baidu Transcoder');
?? ?$is_mobile = false;
?? ?foreach($mobile_agents as $device){
?? ??? ?if(stristr($user_agent,$device) !== FALSE){
?? ??? ??? ?$is_mobile = true;
?? ??? ??? ?break;
?? ??? ?}
?? ?}
?? ?return $is_mobile;
}

使用时,只需要用if(is_mobile())进行判断即可,乌徒帮通过这种方法,实现了让顶部的导航在手机浏览时消失,换为适合手机浏览的小导航,不信你可以用手机访问http://www.utubon.com试试看(触屏智能手机效果更佳哦!)。

在这个函数中,我们通过对比我们已经计划好的一些关键字,和$_SERVER['HTTP_USER_AGENT']进行匹配,如果$_SERVER['HTTP_USER_AGENT']中包含了我们给出的一些关键字中的一个,我们就判定用户在使用手机浏览器访问网站。我们要做的就是搜集这些特殊的关键字,它们是确定用户是否为手机浏览用户的唯一标识。

在函数的开头我们有一句if(trim($user_agent) == '')return true;$_SERVER['HTTP_USER_AGENT']为空的话,我们也断定用户在使用手机浏览器,原因是用户如果用桌面版的浏览器访问网站,一般都会有足够的$_SERVER['HTTP_USER_AGENT']信息,而我在阅读一些资料时,有人提到,中国移动会过滤掉$_SERVER['HTTP_USER_AGENT'],因此网站php程序不会接收到$_SERVER['HTTP_USER_AGENT']信息。

为了在PC浏览器上模拟不同的USER_AGENT,我们可以为Chrome或Firefox装上一些插件,如USER AGENT switcher等,可以设置为一些手机设备,让浏览器的USER_AGENT变为手机设备,从而模拟手机访问网站。

填写个人信息,赶快回复吧!