HowTo: Browser and OS Detection with PHP

A very quick PHP script for detecting browser/device and OS agent strings from the HTTP User Agent variable. This is not 100% reliable because surfers and bots sometimes hide or falsify the user agent string so please use with caution.

Browser and OS Detection Script

This script detects whether the OS/Device is Linux, MacOS, iPad, iPhone, Droid, Unix, Windows or anything else (caught in Unknown). It also detects whether the browser is Chrome, Firefox, Opera or Internet Explorer.

The user agent string is stored in the variable $agent.

The operating system or device is stored in the variable $os.

The browser is stored in $br.

Copy and paste the following code into the top of your PHP file or save it in its own PHP file and use a PHP include to bring it into the file where the $br and $os variables are used:

Use the Script

The detection script checks a web browser’s user agent string for specific words like Chrome, Unix, Windows and Firefox. Here is a basic run though of how to use those user agent strings:

// Action when OS/Device is found
if($os=='Linux')
{
echo 'This is done when the OS/Device is Linux';
}
if($os=='Mac')
{
echo 'This is done when the OS/Device is MacOS';
}
if($os=='iPhone')
{
echo 'This is done when the OS/Device is iPhone';
}
if($os=='iPad')
{
echo 'This is done when the OS/Device is iPad';
}
if($os=='Droid')
{
echo 'This is done when the OS/Device is Droid';
}
if($os=='Unix')
{
echo 'This is done when the OS/Device is Unix';
}
if($os=='Unknown')
{
echo 'This is done when the OS/Device is unknown. This is the failsafe for when an OS/Device is not detected.';
}
// Action when Browser is detected
if($br=='Firefox')
{
echo 'This is done when the Browser is Firefox';
}
if($br=='Chrome')
{
echo 'This is done when the Browser is Chrome';
}
if($br=='Opera')
{
echo 'This is done when the Browser is Opera';
}
if($br=='MSIE')
{
echo 'This is done when the Browser is Microsoft Internet Explorer';
}
if($br=='Unknown')
{
echo 'This is done when the Browser is Unknown. This is the failsafe for when a browser type is not detected';
}
// Action when both browser and OS/Device are detected
if($os=='Linux' && $br=='Firefox')
{
echo 'This is done when the Browser is Firefox and the OS is Linux.';
}
if($os=='Unknown' && $br=='Unknown')
{
echo 'This is done when the Browser is Unknown and the OS is Unknown. This is the catch-the-rest failsafe';
}

It’s a simple script and very easy to use. If you need help, use the message box below to tell me.