how to detect mobile browser using php.

Now a days the usage of mobile device for browsing day by day. So for giving a good reading and browsing experience to the users, most of the websites are having mobile version and computer version. Some of the websites are following responsive design, so that they don’t need to worry about whether a user is coming from a mobile device or a computer. If your website is using mobile version and computer version, you need to detect from which device a user is coming into your site. So that you can redirect the user accordingly. In this article let us check how to detect mobile browser using php.

Here I’m going to explain a very simple php script, that can be used for detect mobile browser very easily. This code can be used in your website for detecting a user is coming to your website using a mobile device or from a computer. Here I’m showing cods in two way. One is using stripos functionality for detecting mobile browser, another is using preg_match for detecting mobile browser.

You can put the php code at the top of your website page. If a user is coming from a mobile device the out put of the function will be “yes”. else if the user is coming from computer the out put of the function will be “no”. If the output of the function is yes you can understand that user is coming from a mobile device, so you can write a redirection to mobile site code after verifying the output of the function.

checking using stripos functionality.

function detect_mobile_browser($agent){

$BAgents = array("iphone","ipad","iPod","android","BlackBerry","Nokia","Mobi","UCWEB");

    foreach($BAgents as $value){

     if(stripos($agent,$value)){

             $agent_res= 1;
             break;
         }

      }
      if($agent_res==1){
           return "yes";
      }else{
         return "no";

      }

}
echo $res=detect_mobile_browser($_SERVER['HTTP_USER_AGENT']);

checking using preg_match functonality.


function detect_mobile_browser($agent){

$BAgents = array("iphone","ipad","iPod","android","BlackBerry","Nokia","Mobi","UCWEB");

    foreach($BAgents as $value){

       $value= "/".$value."/";
         if(preg_match($value,$agent)){
              $agent_res= 1;
             break;
         }

      }

      if($agent_res==1){
           return "yes";
      }else{
           return "no";
      }

}

echo $res=detect_mobile_browser($_SERVER['HTTP_USER_AGENT']);

In this $BAgents array add as much as mobile agent name that you got. So your result will be more accurately. So I hope you can have an idea about how to detect mobile browser using php from this article i will recommend detect mobile browser using stripos functionality rather than using preg_match.