Mobile.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. class Mobile
  5. {
  6. /**
  7. * Handle an incoming request.
  8. *
  9. * @param \Illuminate\Http\Request $request
  10. * @param \Closure $next
  11. * @return mixed
  12. */
  13. public function handle($request, Closure $next)
  14. {
  15. if( $this->isMobile() ){
  16. return $next($request);
  17. }else{
  18. return redirect()->route('pc');
  19. }
  20. }
  21. protected function isMobile()
  22. {
  23. // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
  24. if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
  25. return true;
  26. }
  27. // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
  28. if (isset ($_SERVER['HTTP_VIA'])) {
  29. return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;// 找不到为flase,否则为TRUE
  30. }
  31. // 判断手机发送的客户端标志,兼容性有待提高
  32. if (isset ($_SERVER['HTTP_USER_AGENT'])) {
  33. $clientkeywords = array(
  34. 'mobile',
  35. 'nokia',
  36. 'sony',
  37. 'ericsson',
  38. 'mot',
  39. 'samsung',
  40. 'htc',
  41. 'sgh',
  42. 'lg',
  43. 'sharp',
  44. 'sie-',
  45. 'philips',
  46. 'panasonic',
  47. 'alcatel',
  48. 'lenovo',
  49. 'iphone',
  50. 'ipod',
  51. 'blackberry',
  52. 'meizu',
  53. 'android',
  54. 'netfront',
  55. 'symbian',
  56. 'ucweb',
  57. 'windowsce',
  58. 'palm',
  59. 'operamini',
  60. 'operamobi',
  61. 'openwave',
  62. 'nexusone',
  63. 'cldc',
  64. 'midp',
  65. 'wap'
  66. );
  67. // 从HTTP_USER_AGENT中查找手机浏览器的关键字
  68. if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
  69. return true;
  70. }
  71. }
  72. if (isset ($_SERVER['HTTP_ACCEPT'])) { // 协议法,因为有可能不准确,放到最后判断
  73. // 如果只支持wml并且不支持html那一定是移动设备
  74. // 如果支持wml和html但是wml在html之前则是移动设备
  75. 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')))) {
  76. return true;
  77. }
  78. }
  79. return false;
  80. }
  81. }