PHP判断访问者是PC端还是移动端?

  1. function isMobile()
  2. {
  3. // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
  4. if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
  5. {
  6. return true;
  7. }
  8. // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
  9. if (isset ($_SERVER['HTTP_VIA']))
  10. {
  11. // 找不到为flase,否则为true
  12. return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
  13. }
  14. // 脑残法,判断手机发送的客户端标志,兼容性有待提高
  15. if (isset ($_SERVER['HTTP_USER_AGENT']))
  16. {
  17. $clientkeywords = array ('nokia',
  18. 'sony',
  19. 'ericsson',
  20. 'mot',
  21. 'samsung',
  22. 'htc',
  23. 'sgh',
  24. 'lg',
  25. 'sharp',
  26. 'sie-',
  27. 'philips',
  28. 'panasonic',
  29. 'alcatel',
  30. 'lenovo',
  31. 'iphone',
  32. 'ipod',
  33. 'blackberry',
  34. 'meizu',
  35. 'android',
  36. 'netfront',
  37. 'symbian',
  38. 'ucweb',
  39. 'windowsce',
  40. 'palm',
  41. 'operamini',
  42. 'operamobi',
  43. 'openwave',
  44. 'nexusone',
  45. 'cldc',
  46. 'midp',
  47. 'wap',
  48. 'mobile'
  49. );
  50. // 从HTTP_USER_AGENT中查找手机浏览器的关键字
  51. if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
  52. {
  53. return true;
  54. }
  55. }
  56. // 协议法,因为有可能不准确,放到最后判断
  57. if (isset ($_SERVER['HTTP_ACCEPT']))
  58. {
  59. // 如果只支持wml并且不支持html那一定是移动设备
  60. // 如果支持wml和html但是wml在html之前则是移动设备
  61. if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
  62. {
  63. return true;
  64. }
  65. }
  66. return false;
  67. }

if($this->isMobile()){

//跳转移动端页面

}else{

//跳转PC端页面

}

======================

首先推荐一个php轻量级识别类,Mobile-Detect 专门识别是手机端还是pc端访问网站,这样就可以根据访问的终端类型指向手机浏览器适配的网站还是pc浏览器的网站。

Mobile-Detect官网链接如下MobileDetect

示例链接如下:Mobile-Detect Example

下面是我写得简单的跳转适配PC端还是手机端的代码:

[php]view plaincopy

  1. <?php
  2. require_once 'Mobile_Detect.php'; //注意要引入Mobile_Detect.php 这个类在上文的连接中有下载链接
  3. $detect = new Mobile_Detect;
  4. if($detect->isMobile()){
  5. header('Location: http://127.0.0.1/MobileDetect/MobileDetect/mobile.html', true, 301);
  6. echo "mobile";
  7. }else{
  8. header('Location: http://127.0.0.1/MobileDetect/MobileDetect/pc.html', true, 301);
  9. echo "pc";
  10. }
  11. ?>