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

检测移动设备的php代码,手机访问

发布:smiling 来源: PHP粉丝网  添加日期:2014-06-25 15:33:46 浏览: 评论:0 

如果我们要判断访问网站的是手机用户还是PC用户我们只要获取用户的HTTP_USER_AGENT即可,我先介绍了一个通用的Mobile_Detect,后面两个例子是自己写的希望对各位有帮助.

php代码实例如下:

  1. //使用实例 
  2.  
  3. include 'Mobile_Detect.php'; 
  4. $detect = new Mobile_Detect(); 
  5.  
  6. // Check for any mobile device. 
  7. if ($detect->isMobile()) 
  8.  
  9. // Check for any tablet. 
  10. if($detect->isTablet()) 
  11.  
  12. // Check for any mobile device, excluding tablets. 
  13. if ($detect->isMobile() && !$detect->isTablet()) 
  14.  
  15. if ($detect->isMobile() && !$detect->isTablet()) 
  16.  
  17. // Alternative to $detect->isAndroidOS() 
  18. $detect->is('AndroidOS'); 
  19.  
  20. // Batch usage 
  21. foreach($userAgents as $userAgent){ 
  22.   $detect->setUserAgent($userAgent); 
  23.   $isMobile = $detect->isMobile(); 
  24. } 
  25.  
  26. // Version check. 
  27. $detect->version('iPad'); // 4.3 (float) 

php判断手机访问,代码如下:

  1. ua = strtolower($_SERVER['HTTP_USER_AGENT']); 
  2.  
  3. $uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|wap)/i"; 
  4.  
  5. if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap')) 
  6. { 
  7.     $Loaction = 'wap/'; 
  8.  
  9.     if (!emptyempty($Loaction)) 
  10.     { 
  11.         ecs_header("Location: $Loactionn"); 
  12.  
  13.         exit; 
  14.     } 
  15.  
  16. } 
  17.  
  18. /**   
  19. * 自定义 header 函数,用于过滤可能出现的安全隐患
  20. *   
  21. * @param   string  string  内容   
  22. *   
  23. * @return  void   
  24. **/   
  25. function ecs_header($string, $replace = true, $http_response_code = 0)   
  26. {   
  27.     if (strpos($string, '../upgrade/index.php') === 0)   
  28.     {   
  29.         echo '<script type="text/javascript">window.location.href="' . $string . '";</script>';   
  30.     }   
  31.     $string = str_replace(array("r", "n"), array('', ''), $string);   
  32.    
  33.     if (preg_match('/^s*location:/is', $string))   
  34.     {   
  35.         @header($string . "n", $replace);   
  36.    
  37.         exit();   
  38.     }   
  39.    
  40.     if (emptyempty($http_response_code) || PHP_VERSION < '4.3')   
  41.     {   
  42.         @header($string, $replace);   
  43.     }   
  44.     else 
  45.     {   
  46.         @header($string, $replace, $http_response_code);   
  47.     }   
  48. }  

js代码如下:

  1. var isIPhone = /iPhone/i.test(navigator.userAgent), 
  2.  isIPad = /iPad/i.test(navigator.userAgent), 
  3.  isAndroid = /android/i.test(navigator.userAgent); 
  4. var isIOS = isIPhone  || isIPad; 
  5. alert( 
  6.  "iPhone? "+isIPhone+"tr"+ 
  7.  "iPad? "+isIPad+"tr"+ 
  8.  "Android? "+isAndroid+"tr"+ 
  9.  "iOS? "+isIOS 
  10. ); 

Tags: 移动设备 PHP手机访问

分享到: