PHP 

Introduction

In this example we will see how to detect Operating System using PHP technology. We are going to use browser’s HTTP_USER_AGENT that gives lots of information about the operating system but here we will only detect operating system type, such as, Windows, Mac, Linux, Ubuntu, Mobile etc. We 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

Example with Source Code

Creating Project Directory

Create a project root directory called php-os-detect and put it under Apache 2.4 http server’s htdocs folder.

Detecting Operating System

Use below PHP code to detect Operating System. Here we are 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
    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:

detect operating system using php

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

You can download source code.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *