Wednesday, September 18, 2013

detect mobile browser using php


This tutorial provide a script to detect mobile browser and according to that create your moble version website , Then use this script to redirect to own moble version site.

<?php

   echo $_SERVER['HTTP_USER_AGENT'];       // detect 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.

Method - 1:

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']);

Method - 2:

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']);


No comments:

Post a Comment