Determining the visitor's OS in PHP

1.9k Views Asked by At

I am trying to get the OS of the visitor in PHP(Codeingiter). I tried https://github.com/serbanghita/Mobile-Detect. It worked for me 70% of the time. But still it's not detecting accurately. A good amount of Android traffic is not detected as mobile or tablet.

3

There are 3 best solutions below

2
Jaume Mussons Abad On

There's no accurate way to detect the Operating system via php or any other server language.

This kind of detection normally relies on the browser agent, but it can be faked and most of the time does not have enought information.

2
medicm On

You have to add checks for other devices like iPads and others that I missed...

$hua = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT');
$os = 'I have no idea...';

if(preg_match('/android/i', $hua)) {
    $os = 'Android';
} elseif (preg_match('/linux/i', $hua)) {
    $os = 'Linux';
} elseif (preg_match('/iphone/i', $hua)) {
    $os = 'iPhone';
} elseif (preg_match('/macintosh|mac os x/i', $hua)) {
    $os = 'Mac';
} elseif (preg_match('/windows|win32/i', $hua)) {
    $os = 'Windows';
}
echo $os;
1
Viral Patel On

The User Agent Class Library in CodeIgniter Provides functions to carry out your task. You can find more details about them here : User Agent Class Library

Specifically look for platform() function to detect the OS of the visitor.