Last updated on January 25th, 2022 at 07:02 pm

This code will help you to Detect the operating system [os] used by your website visitor using PHP. Lets be honest here it is not the perfect script but it should work. Feel free to add your own logic with new OS detection according to your requirements.

<?php
function OSflavour($userAgent) {
  // Create list of operating systems with operating system name as array key
	$myos = array (
		'iPhone' => '(iPhone)',
		'Windows 3.11' => 'Win16',
		'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)', // Use regular expressions as value to identify operating system
		'Windows 98' => '(Windows 98)|(Win98)',
		'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
		'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
		'Windows 2003' => '(Windows NT 5.2)',
		'Windows Vista' => '(Windows NT 6.0)|(Windows Vista)',
		'Windows 7' => '(Windows NT 6.1)|(Windows 7)',
		'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
		'Windows ME' => 'Windows ME',
		'Open BSD'=>'OpenBSD',
        'Ubuntu' => '(Ubuntu)',
		'Sun OS'=>'SunOS',
		'Linux'=>'(Linux)|(X11)',
		'Macintosh'=>'(Mac_PowerPC)|(Macintosh)',
		'Android'=> '(Android)',
		'Mac' => '(Safari)',
		'QNX'=>'QNX',
		'BeOS'=>'BeOS',
		'OS/2'=>'OS/2',
		'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)'
	);

	foreach($myos as $os=>$data){ // Loop through $oses array
    // Use regular expressions to check operating system type
		if(preg_match($data, $userAgent)) { // Check if a value in $oses array matches current user agent.
		return "Your OS is:-<b>".$os."</b>"; // Operating system was matched so return $oses key
		}
	}
	return 'Unknown'; // Cannot find operating system so return Unknown
}
echo OSflavour($_SERVER['HTTP_USER_AGENT']);
?>

DEMO

Leave a Reply

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