Al jazary icon and logo Al jazary

php detect mobile browser user agent using strstr function - Al jazary

published 07 Jul 2016

php detect mobile browser user agent using strstr function

each browser request to web server it send http header along with user-agent, this user-agent is vary including data for browser like browser name, operation system and more. search engine also using name like Googlebot or Bingbot in their user agent, with this we can easier to serve dynamic content that showing data only for choosed one.

in javascript we activate function or animation that only run except mobile device to increase mobile performa, and in php we can produce dynamic content that how we show it to mobile user and another, this will reduce data tranfer and make our site have a better speed load.

php function strstr detect mobile browser example

<?php
//ready a function call.
function checkUA( $agent , $list ){
  $status=0;
  foreach( $list as $li ){
    if( strstr( $agent , $li )){
      $status = 1;
    }
  }
  return $status;
}

$agent = $_SERVER["HTTP_USER_AGENT"];
$list = array("Android","iPhone","Windows Phone","BlackBerry"); 
$ismobile = checkUA( $agent , $list );

if($ismobile == 1 ){
  //execute code for mobile...
} else {
  //execute if they are not mobile...
}
?>

first we create a function that ready for our request, why use this function? because sometime we often check status of user agent to execute another syntax so will be good to prepare it. in function we loop through $list that hold an array list, each of them is checking using strstr function, in default we has set $status=0 and then after loop it will change if our list is detected in user-agent browser. it wil return true if exist and return false otherwise. then if return true, our function continues to set $status=1; than after loop finish we orders our checkUA function to return value of $status.

so now $ismobile will hold same value as that function, value is 1 or 0, which 1 meaning mobile browser detected and 0 is not detected. in future code writing simply we can use if/else operator to execute our dynamic content and all is gone as as we wanted.

mobilebrowser updated 07 Jul 2016

0 total comments

Add Comment

Sitemap

    templates

    htaccess

    php

    tools

    articles

    hardware

Top articles