How to detect Operating System using PHP in webpage

Author: | Posted in Code Tricks, PHP, Quick Tips No comments

In this tutorial we will learn how to detect operating system using PHP in a webpage.
Because some time we need to show some links on webpage according to operating system in which it opened.

In PHP we can determine operating system information using webpage’s HTTP_USER_AGENT header.

Using below code in a PHP webpage we can determine operating system information.

Code Example:

<?php
$agent = $_SERVER['HTTP_USER_AGENT'];
if(preg_match('/Linux/',$agent)) $os = 'Linux';
elseif(preg_match('/Win/',$agent)) $os = 'Windows';
elseif(preg_match('/Mac/',$agent)) $os = 'Mac';
if(preg_match('/Android/',$agent)) $os = 'Android';
elseif(preg_match('/iPhone/',$agent)) $os = 'iPhone';
elseif(preg_match('/iPad/',$agent)) $os = 'iPad';
else $os = 'UnKnown'; 
echo $os;
?>

 

Note: It may possible that above code may not work some time or may detect wrong information. Because it is completely depends on way of implementation of that webpage.