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

Tags: HTTP_USER_AGENT 是否为手机访问

分享到: