TP3.2.x判断手机端访问并设置默认访问模块的方法 - ThinkPHP框架

时间:2021-09-19 11:00:40

手机端访问时调用Wap手机模块,实现在手机端访问时展示出手机网站,无需跳转域名
首先我们在./Application/Common/Conf/ 目录下建立两个公共配置文件:config.php 和config_wap.php

config.php 中:

  1. return array(
  2. 'DEFAULT_MODULE'=>'Index',
  3. 'DEFAULT_CONTROLLER'=>'Index',
  4. 'DEFAULT_ACTION'=>'index',
  5. )
复制代码

config_wap.php 中:

  1. return array(
  2. 'DEFAULT_MODULE'=>'Wap',
  3. 'DEFAULT_CONTROLLER'=>'Index',
  4. 'DEFAULT_ACTION'=>'index',
  5. )
复制代码

然后在入口文件 index.php 中加入手机端判断方法(建议放到最下面):

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

然后,我们开始用关键的APP_STATUS来调用不同的模块:
在index.php文件中的21行后面也就是“定义应用目录”结束后,加入代码:

  1. if(is_mobile_request()){
  2. define('APP_STATUS','config_wap');
  3. }else{
  4. define('APP_STATUS','Index');
  5. }
复制代码

大功告成。
参考文档:http://document.thinkphp.cn/manual_3_2.html#load_config