PHP Browser Detection

Retrieving the current user agent using PHP is done via the use of the $_SESSION super global array. The following line of code will print off your user agent.

echo $_SERVER['HTTP_USER_AGENT'];

For Firefox on Windows this user agent will look like this.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12

This is all fine, but what about getting more meaningful information, like just the version number. Here is a function that will get the version number (major or minor) from anyone visiting a page with Internet Explorer.

function ieVersion($minor=false){
 preg_match('/MSIE ([0-9]\.[0-9])/', $_SERVER['HTTP_USER_AGENT'], $match);
 if (!isset($match[1])) {
  return -1;
 } else {
  if ($minor) {
   return $match[1];
  } else {
   return floor($match[1]);
  }
 }
}

This will work for all of the different versions of Internet Explorer, but what about other browsers. One solution might be to create lots of functions that each checked the user agent string for a specific string. However, this is just overcomplicating things. Here is a function that will detect the user agent and version number and present it in a nice form.

function userAgent($minor=false)
{
 $agents = array('MSIE' => '/MSIE ([0-9]\.[0-9])/',
  'Firefox' => '/Firefox\/([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*)/',
  'Opera' => '/Opera\/([0-9]*\.[0-9])/',
  'Safari' => '/Version\/([0-9]*\.[0-9]*\.?[0-9]*)/');
 foreach($agents as $agent=>$pattern){
  preg_match($pattern, $_SERVER['HTTP_USER_AGENT'], $match);
  if (isset($match[1])) {
   if ($minor) {
    return $agent . ' ' . $match[1];
   } else {
    return $agent . ' ' . floor($match[1]);
   };
  };
 };
 return 'Unknown browser';
}

This only checks for four different browser types so if you want to add more then just append the name and pattern to match to the array. To run this function and find out the browser version of a visitor use the following code.

echo userAgent(true);

From the user agent example given above this will output Firefox 2.0.0.12.

This is a very simplified mechanism of fetching user agents as it just gives a version number. To get a very clear idea about the capabilities of the browser you can use the get_browser() function. By passing a user agent string into the function it will return an array detailing everything that the browser is capable of, right down to whether cookies or JavaScript is enabled. The only problem is that a browser.ini file is needed to decode the user agent string, and this is not always available.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 19 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.