提示信息

PHP自动识别当前使用移动终端

无语 已关注

虽然现在利用jquery可以准确地判断出当前使用的是那种客户端,但是有时候根据功能和需求,我们可能需要用php来判断当前程序运行的环境,jquery在这里就不说了,这里直接讲讲php是怎么实现的,希望对大家有所帮助。

1.首先来判断当前运行环境是pc(电脑端)还是sp(手机,ipad端)

  1. class self_test {
  2. const PC = 'pc';
  3. const SP = 'sp';
  4. private $_splist = array('iPhone','Android','iPod','iPad','Tizen');//设置经常使用的sp终端,暂时常用的sp端就这几种,如果有的话大家也可以增加
  5. private $terminal;
  6. public function __construct(){
  7. $this->setTerminal();//通过setTerminal()方法获取到$terminal变量的值
  8. }
  9. /*
  10. * function setTerminal()
  11. * 获取终端信息
  12. * @return string
  13. */
  14. private function setTerminal(){
  15. $isSp = false;
  16. foreach($this->_splist as $spname){
  17. if (strstr($_SERVER['HTTP_USER_AGENT'], $spname)) {
  18. $isSp = true;
  19. break;
  20. }
  21. }
  22. return $this->terminal = ($isSp) ? self::SP : self::PC;
  23. }
  24. /*
  25. * function PC_SP()
  26. * 输出终端信息
  27. * @return string
  28. */
  29. public function PC_SP(){
  30. return $this->terminal;
  31. }
  32. }
  33. $str = new self_test();
  34. echo $str->PC_SP();//输出目前客户使用的是PC还是SP

2.准确判断当前的运行环境并输出客户端环境

  1. class self_test {
  2. const PC = 'pc';
  3. const SP = 'sp';
  4. private $_splist = array('iPhone','Android','iPod','iPad','Tizen');//设置经常使用的sp终端,暂时常用的sp端就这几种,如果有的话大家也可以增加
  5. private $environment;
  6. public function __construct(){
  7. $this->setEnvironment();//通过setEnvironment()方法获取到$terminal变量的值
  8. }
  9. /*
  10. * function environment()
  11. * 输出终端信息
  12. * @return string
  13. */
  14. public function environment(){
  15. return $this->environment;
  16. }
  17. /*
  18. * function setEnvironment()
  19. * 获取终端信息
  20. * @return string
  21. */
  22. private function setEnvironment(){
  23. $isSp = self::PC;//如果是PC端,就不需要判断是安卓还是apple了,所以只输出pc就可以
  24. foreach($this->_splist as $spname){
  25. if (strstr($_SERVER['HTTP_USER_AGENT'], $spname)) {
  26. $isSp = $spname;
  27. break;
  28. }
  29. }
  30. return $this->environment = $isSp;
  31. }
  32. }
  33. $str = new self_test();
  34. echo $str->environment();//输出目前客户使用的终端
无语 关注 已关注

最近一次登录:2020-04-12 22:44:23   

暂时还没有签名,请关注我或评论我的文章
×
分享到朋友圈