PHP automatically identifies the currently used mobile terminal

  • 2021-10-13 06:43:03
  • OfStack

Although jquery can be used to accurately judge which client is currently used, sometimes according to functions and requirements, we may need to use php to judge the current running environment of the program. jquery will not be mentioned here, but how php is implemented will be directly discussed here, hoping to be helpful to everyone.

Let's first judge whether the current running environment is pc (computer side) or sp (mobile phone side, ipad side)


class self_test { 
  
 const PC = 'pc'; 
  
 const SP = 'sp'; 
  
 private $_splist = array('iPhone','Android','iPod','iPad','Tizen');// Set the frequently used sp Terminal , Temporarily commonly used sp This is the only one , If there is, you can also increase it  
 
 private $terminal; 
  
 public function __construct(){ 
  $this->setTerminal();// Pass setTerminal() Method gets the $terminal Value of variable  
 } 
  
 /* 
  * function setTerminal() 
  *  Acquiring terminal information  
  * @return string 
  */ 
  
 private function setTerminal(){ 
  $isSp = false; 
  foreach($this->_splist as $spname){ 
   if (strstr($_SERVER['HTTP_USER_AGENT'], $spname)) { 
    $isSp = true; 
    break; 
   } 
  } 
  return $this->terminal = ($isSp) ? self::SP : self::PC; 
 } 
  
 /* 
  * function PC_SP() 
  *  Output terminal information  
  * @return string 
  */ 
 public function PC_SP(){ 
  return $this->terminal; 
 } 
} 
 
$str = new self_test(); 
echo $str->PC_SP();// Output is currently used by customers PC Or SP 

2. Accurately judge the current running environment and output the client environment


class self_test {  
 const PC = 'pc';  
 const SP = 'sp';  
 private $_splist = array('iPhone','Android','iPod','iPad','Tizen');// Set the frequently used sp Terminal , Temporarily commonly used sp This is the only one , If there is, you can also increase it  
 private $environment;  
 public function __construct(){ 
  $this->setEnvironment();// Pass setEnvironment() Method gets the $terminal Value of variable  
 } 
  
 /* 
  * function environment() 
  *  Output terminal information  
  * @return string 
  */ 
 public function environment(){ 
  return $this->environment; 
 } 
  
 /* 
  * function setEnvironment() 
  *  Acquiring terminal information  
  * @return string 
  */ 
 private function setEnvironment(){ 
  $isSp = self::PC;// If it is PC End, you don't need to judge whether it is Android or apple So only output pc You can  
  foreach($this->_splist as $spname){ 
   if (strstr($_SERVER['HTTP_USER_AGENT'], $spname)) { 
    $isSp = $spname; 
    break; 
   } 
  } 
  return $this->environment = $isSp; 
 } 
} 
$str = new self_test(); 
echo $str->environment();// Output the terminal currently used by the customer  

The above code is the content that is posted and shared after running successfully, so we can debug in our own environment.


Related articles: