PHP is a very versatile web programming language that allows web server to serve dynamic content to visitors. PHP can detect and identify the type and version of web browser that visitor used to browse the web page in order to output and display browser-specific targeted content such as custom text, and especially to provide compatibility for older version or non-standard compliant browser with custom HTML or CSS markup.

PHP’s $_SERVER global variable provides various server and execution environment information, including HTTP_USER_AGENT element which contains browser-specific user-agent, which can be used to identify the web browser used to accessing the page on current request. A typical user-agent looks like:

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543 Safari/419.3

Every user string has a unique identifier which shows which web browser is making the request for the web page. Thus, it’s possible to detect and single out a specific browser by comparing the value return by $_SERVER[‘HTTP_USER_AGENT’] variable against the browser-specific user agent string.

Here’s an example code which can be used in PHP to detect and retrieve the web browser type as variable or used directly in comparison function.

<?php

$user_agent = $_SERVER['HTTP_USER_AGENT']; 

if (preg_match('/MSIE/i', $user_agent)) { 
   echo "Internet Explorer";
} else {
   echo "Non-IE Browser";
} 

?>

Script above will detect if the visitor is using IE (Internet Explorer) browser. To code can be expanded to detect additional browser with elseif conditional tag. To check for other browser, just replace the MSIE with the user agent name for other browser. Some popular web browsers can be identified with the following string:

Internet Explorer: MSIE
Mozilla Firefox: Firefox
Google Chrome: Chrome
Apple Safari: Safari
Opera: Opera
Netscape Navigator: Netscape
Flock: Flock
Lynx: Lynx

Tip: It’s possible to use “strtolower” to make the $user_agent to all lower case so that all PHP script does not miss out on browsers which do not use standard naming convention in user agent. In this case, remember to compare against user agent string which is lower case too, such as msie, firefox and etc.