当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP根据HTTP_USER_AGENT判断客户端访问是否为手机访问

发布:smiling 来源: PHP粉丝网  添加日期:2014-06-26 08:45:19 浏览: 评论:0 

现在web发展速度非常快,各种响应式的站点越来越多,除了APP外,在平时可能需要根据客户终端访问来加载不同时模板或跳转到不同时的域名下,现在分享一个函数,可以做到这样判断.android、ios和wp都已经测试过.

PHP实例代码如下:

  1. //判断moblie 
  2. function is_mobile() 
  3.     $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : ''
  4.  
  5.     $mobile_browser = '0'
  6.  
  7.     if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom|ios)/i'strtolower($_SERVER['HTTP_USER_AGENT']))) 
  8.         $mobile_browser++; 
  9.  
  10.     if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false)) 
  11.         $mobile_browser++; 
  12.  
  13.     if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) 
  14.         $mobile_browser++; 
  15.  
  16.     if(isset($_SERVER['HTTP_PROFILE'])) 
  17.         $mobile_browser++; 
  18.  
  19.     $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)); 
  20.     $mobile_agents = array
  21.                         'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac'
  22.                         'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno'
  23.                         'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-'
  24.                         'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-'
  25.                         'newt','noki','oper','palm','pana','pant','phil','play','port','prox'
  26.                         'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar'
  27.                         'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-'
  28.                         'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp'
  29.                         'wapr','webc','winw','winw','xda','xda-' 
  30.                         ); 
  31.  
  32.     if(in_array($mobile_ua$mobile_agents)) 
  33.         $mobile_browser++; 
  34.  
  35.     if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) 
  36.         $mobile_browser++; 
  37.     // Pre-final check to reset everything if the user is on Windows 
  38.     if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false) 
  39.         $mobile_browser=0; 
  40.  
  41.     // But WP7 is also Windows, with a slightly different characteristic 
  42.     if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) 
  43.         $mobile_browser++; 
  44.  
  45.     if($mobile_browser>0) 
  46.         return true; 
  47.     else 
  48.         return false; 

Tags: HTTP_USER_AGENT 是否为手机访问

分享到: