Detect the browser in PHP

By Faruque Ahamed Mollick

In this tutorial, we are going to see how to detect the browser of a user using PHP programming language. Here we are going to create our own custom PHP function which we can call later to get the browser.

We will use the $_SERVER global variable. The $_SERVER[‘HTTP_USER_AGENT’] can returns various information related to the browser.

Now below is our PHP function that we can use to display the browser:

<?php

function get_the_browser()
{

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)
   return 'Internet explorer';
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false)
    return 'Internet explorer';
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false)
   return 'Mozilla Firefox';
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false)
   return 'Google Chrome';
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false)
   return "Opera Mini";
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false)
   return "Opera";
 elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false)
   return "Safari";
 else
   return 'Other';

}


?>

In the above code, we are checking each possible browser that may be and return the browser name. Here we haven’t checked the Mozilla because of most of the browser using this as the user agent string.

Below is how to display the browser name on our web page:

echo get_the_browser();

We will able to see the browser.

Note that, this will always not going to give us the right information. Server-side browser detection may wrong. So, client-side browser detection is better than server-side detection. We can use JavaScript to detect browser from the client side.

Leave a Reply

Your email address will not be published. Required fields are marked *