PHP Browser Detection

27th March 2008 - 3 minutes read time

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.

  1. function ieVersion($minor=false){
  2. preg_match('/MSIE ([0-9]\.[0-9])/', $_SERVER['HTTP_USER_AGENT'], $match);
  3. if (!isset($match[1])) {
  4. return -1;
  5. } else {
  6. if ($minor) {
  7. return $match[1];
  8. } else {
  9. return floor($match[1]);
  10. }
  11. }
  12. }

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.

  1. function userAgent($minor=false)
  2. {
  3. $agents = array('MSIE' => '/MSIE ([0-9]\.[0-9])/',
  4. 'Firefox' => '/Firefox\/([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*)/',
  5. 'Opera' => '/Opera\/([0-9]*\.[0-9])/',
  6. 'Safari' => '/Version\/([0-9]*\.[0-9]*\.?[0-9]*)/');
  7. foreach($agents as $agent=>$pattern){
  8. preg_match($pattern, $_SERVER['HTTP_USER_AGENT'], $match);
  9. if (isset($match[1])) {
  10. if ($minor) {
  11. return $agent . ' ' . $match[1];
  12. } else {
  13. return $agent . ' ' . floor($match[1]);
  14. };
  15. };
  16. };
  17. return 'Unknown browser';
  18. }

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.