Browser Detectors
Shobhan Challa on 2002 April 20
Shobhan Challa on 2002 April 20
With many browsers on the market today, web designers feel a great pressure to make their code work on all and each of them. In this short article, I'll demonstrate you how easily PHP can detect your user's enviroment
.Browser
The most important thing for most of us is to detect the browser the user is using and show the appropriate page to him. A common way to do it is - no, not by using lengthy JavaScripts, but with this very simple PHP code:
<?php
if (stristr($_SERVER['HTTP_USER_AGENT'],"MSIE")){
header("Location: ie.php");
}
else {
header("Location: ns.php");
}
?>
The $_SERVER['HTTP_USER_AGENT'] produces a string similar to this one when run in IE:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; (R1 1.1))
NOTE: before PHP v4.1.0 the enviroment variable $_SERVER['HTTP_USER_AGENT'] did not exists, $HTTP_USER_AGENT was containing this info.
The variable $_SERVER['HTTP_USER_AGENT'] is pre-set in all PHP pages by your webserver , so that you can always access it within your scripts. We use the stristr() (case insensitive string search) to check the existence of MSIE in the browser's name. When the stristr() function encounters the word MSIE in the broswer's identification string ($_SERVER['HTTP_USER_AGENT']), it will redirect the user to the specific page.
Operating System
As you could already guess, $_SERVER['HTTP_USER_AGENT'] talks about the user's platform as well. We can do the same as above to find the OS out:
<?php
if (stristr($_SERVER['HTTP_USER_AGENT'],"WIN")){
header("Location: windows.php");
}
else {
header("Location: unix.php");
}
?>
The full code
Heres the browser_detector.php script. What it primarely does is lodaing the right Cascading Style Sheet container to the specific browser.
<?php
if (stristr($HTTP_USER_AGENT,"WIN")) {
// windows
if (stristr($HTTP_USER_AGENT,"MSIE")) {
// MSIE
echo '<link rel="stylesheet" type="text/css" href="ie.css">';
} else {
// if Netscape
echo '<link rel="stylesheet" type="text/css" href="ns.css">';
}
}
else {
// linux
echo '<link rel="stylesheet" type="text/css" href="linux.css">';
}
?>
One can easily add his/her routines and can extend this functionality. it is all up to your invention.
Reccomendations
If you like to experiment some more then check out the get_browser() function of PHP. This function acn greatly reduce our work of detection. It returns you an array containing all kind of usefull info about the platform, browser, majorversion, minorversion, cookies, javascript and much more. But keep in mind that get_browser() function uses browscap.ini file to determine the capabiliities of the users browser, and that file might be sort of tricky to set up.
