您所在的位置:小祥子 » 编程 » PHP » 正文

PHP判断当前用户是否为手机/电脑用户的方法

时间:2015-02-11 编辑:本站 来源:本站原创

先看代码,代码如下,如果是手机用户则返回值为mobile

function browser()
{
 switch(TRUE)
 {
 // Apple/iPhone browser renders as mobile
 case (preg_match('/(apple|iphone|ipod)/i', $_SERVER['HTTP_USER_AGENT']) && preg_match('/mobile/i', $_SERVER['HTTP_USER_AGENT'])):
 $browser = "mobile";
 break;
 // Other mobile browsers render as mobile
 case (preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera 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'])):
 $browser = "mobile";
 break;
 // Wap browser
 case (((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'text/vnd.wap.wml') > 0) || (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0)) || ((isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])))):
 $browser = "mobile";
 break;
 // Shortend user agents
 case (in_array(strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,3)),array('lg '=>'lg ','lg-'=>'lg-','lg_'=>'lg_','lge'=>'lge')));
 $browser = "mobile";
 break;
 // More shortend user agents
 case (in_array(strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)),array('acs-'=>'acs-','amoi'=>'amoi','doco'=>'doco','eric'=>'eric','huaw'=>'huaw','lct_'=>'lct_','leno'=>'leno','mobi'=>'mobi','mot-'=>'mot-','moto'=>'moto','nec-'=>'nec-','phil'=>'phil','sams'=>'sams','sch-'=>'sch-','shar'=>'shar','sie-'=>'sie-','wap_'=>'wap_','zte-'=>'zte-')));
 $browser = "mobile";
 break;
 // Render mobile site for mobile search engines
 case (preg_match('/Googlebot-Mobile/i', $_SERVER['HTTP_USER_AGENT']) || preg_match('/YahooSeeker\/M1A1-R2D2/i', $_SERVER['HTTP_USER_AGENT'])):
 $browser = "mobile";
 break;
 }
 return $browser;
}

使用方法如下(如果是手机用户,那么就跳转到wap.xiaoxiangzi.com)

if(browser()=="mobile" ){ 
 header("location:wap.xiaoxiangzi.com");
}