当前位置:首页 > PHP教程 > PHP常见问题

php网站判断用户是否是手机访问的方法

随着移动设备的普及,网站也会迎来越来越多移动设备的访问。用适应pc的页面,很多时候对手机用户不友好,那么有些时候,我们需要判断用户是否用手机访问,如果是手机的话,就跳转到指定的手机友好页面。这里就介绍一下,如何判断用户是否用手机访问。

自定义的函数如下:

$agent = check_wap(); if( $agent ) { header('location: http://www.jb51.net'); exit; } // check if wap function check_wap(){ // 先检查是否为wap代理,准确度高 if(stristr($_server['http_via'],"wap")){ return true; } // 检查浏览器是否接受 wml. elseif(strpos(strtoupper($_server['http_accept']),"vnd.wap.wml") > 0){ return true; } //检查user_agent elseif(preg_match('/(blackberry|configuration/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |googlebot-mobile|yahooseeker/m1a1-r2d2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_server['http_user_agent'])){ return true; } else{ return false; } }

再来一个从php框架剥离的判断是否为手机移动终端的函数:(经过测试,很全面,推荐使用)

function is_mobile_request() { $_server['all_http'] = isset($_server['all_http']) ? $_server['all_http'] : ''; $mobile_browser = '0'; if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_server['http_user_agent']))) $mobile_browser++; if((isset($_server['http_accept'])) and (strpos(strtolower($_server['http_accept']),'application/vnd.wap.xhtml+xml') !== false)) $mobile_browser++; if(isset($_server['http_x_wap_profile'])) $mobile_browser++; if(isset($_server['http_profile'])) $mobile_browser++; $mobile_ua = strtolower(substr($_server['http_user_agent'],0,4)); $mobile_agents = array( 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac', 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno', 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-', 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-', 'newt','noki','oper','palm','pana','pant','phil','play','port','prox', 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar', 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-', 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp', 'wapr','webc','winw','winw','xda','xda-' ); if(in_array($mobile_ua, $mobile_agents)) $mobile_browser++; if(strpos(strtolower($_server['all_http']), 'operamini') !== false) $mobile_browser++; // pre-final check to reset everything if the user is on windows if(strpos(strtolower($_server['http_user_agent']), 'windows') !== false) $mobile_browser=0; // but wp7 is also windows, with a slightly different characteristic if(strpos(strtolower($_server['http_user_agent']), 'windows phone') !== false) $mobile_browser++; if($mobile_browser>0) return true; else return false;


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!