want to join us? register, it's easy | help

Detecting The User's Browser

Detecting The User's Browser

Introduction

When a browser accesses any page on your website, it sends a user-agent string to the server. In PHP, this string is stored in the $_SERVER superglobals array:

$_SERVER['HTTP_USER_AGENT']

Detecting Browsers

Internet Explorer 7.0 on Vista uses this user-agent string:

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)

and Firefox v.2.0.0.1 uses this user-agent string:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1

To detect a browser using Firefox, we can simply can the user-agent string for the term "firefox" since every version of Firefox since 1.0 contains this term.

To detect Internet Explorer we can use this function:

function isExplorer()
{
 if (!isset($_SERVER['HTTP_USER_AGENT'])){
  return null;
 }
	
 $agent = $_SERVER['HTTP_USER_AGENT'];
 
 if (eregi("MSIE", $agent)){
  return true;
 }
			
 return false;
}

We can further expand this code to detect other browsers if we know the various user-agent strings. For a complete list of this, Wikipedia has an extensive list

Here is a small class that will detect some popular browsers:

<?php
 
class Browser 
{
	function getPlatform()
	{
		if (!isset($_SERVER['HTTP_USER_AGENT'])){
			return null;
		}
		
		$agent = $_SERVER['HTTP_USER_AGENT'];
		
		if (eregi("win", $agent)){
			return "Windows";
		}
		
		if (eregi("mac", $agent)){
			return "Mac";
		}
		
		if (eregi("linux", $agent)){
			return "Linux";
	        }
			
		return "Unknown";
	}
	
	function isFirefox()
	{
		if (!isset($_SERVER['HTTP_USER_AGENT'])){
			return null;
		}
		
		$agent = $_SERVER['HTTP_USER_AGENT'];
		
		if (eregi("Firefox", $agent)){
			return true;
		}
		
		return false;
	}
	
	
	function isExplorer()
	{
	        if (!isset($_SERVER['HTTP_USER_AGENT'])){
			return null;
		}
		
		$agent = $_SERVER['HTTP_USER_AGENT'];
		
		if (eregi("MSIE", $agent)){
			return true;
		}
		
		return false;
	}
	
}
?>

So, to check whether the user is using firefox you would write:

<?php
 
 if (Browser::isFirefox()){
   /* your code goes here */
 }
 
?>

Now you should be able to detect the user's browser using PHP. This can be useful if you need to switch your style sheet to deal with different browsers.