Introduction
In this example I will show you how to detect Operating System using PHP technology. I am going to use browser’s HTTP_USER_AGENT
that gives lots of information about the operating system but here I will only detect operating system type, such as, Windows, Mac, Linux, Ubuntu, Mobile etc. I won’t detect further details, such as, what is the version of Windows (for example, Windows 8, or 10 etc.).
Prerequisites
Apache 2.4, PHP 7.3.5, 7.4.3
Project Directory
Create a project root directory called php-os-detection under Apache 2.4 http server’s htdocs folder.
Detect Operating System
Use below PHP code to detect Operating System. Here I am using HTTP_USER_AGENT
to guess the operating system.
<?php
function get_operating_system() {
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$operating_system = 'Unknown Operating System';
//Get the operating_system name
if (preg_match('/linux/i', $u_agent)) {
$operating_system = 'Linux';
} elseif (preg_match('/macintosh|mac os x|mac_powerpc/i', $u_agent)) {
$operating_system = 'Mac';
} elseif (preg_match('/windows|win32|win98|win95|win16/i', $u_agent)) {
$operating_system = 'Windows';
} elseif (preg_match('/ubuntu/i', $u_agent)) {
$operating_system = 'Ubuntu';
} elseif (preg_match('/iphone/i', $u_agent)) {
$operating_system = 'IPhone';
} elseif (preg_match('/ipod/i', $u_agent)) {
$operating_system = 'IPod';
} elseif (preg_match('/ipad/i', $u_agent)) {
$operating_system = 'IPad';
} elseif (preg_match('/android/i', $u_agent)) {
$operating_system = 'Android';
} elseif (preg_match('/blackberry/i', $u_agent)) {
$operating_system = 'Blackberry';
} elseif (preg_match('/webos/i', $u_agent)) {
$operating_system = 'Mobile';
}
return $operating_system;
}
echo get_operating_system();
?>
Testing the Application
First run your Apache 2.4 http server executing httpd.exe
by navigating the directory apache2.4 installation directory/bin
from the cmd prompt.
Now execute the above PHP file into browser you will see below output:

Here I am using Windows operating system, so I got the output as Windows
. You may get same or different depending upon your operating system you use.
Source Code
Thanks for reading.