Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest Way OS Detection With PHP?

Tags:

php

user-agent

I'm trying to figure out the visitor's OS is either a Windows, Mac or Linux using PHP(I don't need the version, distro info.. etc). There's several methods out there however they look a bit too complicated for this simple requirement.

Are there any simple ways that could provide this sort of information yet still being quite reliable?

Thanks in advance.

like image 707
user435216 Avatar asked Nov 05 '10 09:11

user435216


People also ask

How does PHP detect operating system?

php_uname() returns a description of the operating system PHP is running on. This is the same string you see at the very top of the phpinfo() output. For the name of just the operating system, consider using the PHP_OS constant, but keep in mind this constant will contain the operating system PHP was built on.

How to detect browser in PHP?

The get_browser() function in PHP is an inbuilt function that is used to tell the user about the browser's capabilities. This function looks up the user's browscap. ini file and returns the capabilities of the user's browser.

What is HTTP_ user_ agent?

It's just a string that a browser optionally sends to the server. Firefox can let you change the string entirely via the about:config page by modifying/creating the string general. useragent.


2 Answers

<?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';
else $os = 'UnKnown';


echo $os;

?>
like image 153
Ali Alnoaimi Avatar answered Oct 17 '22 11:10

Ali Alnoaimi


For an easy solution have a look here. The user-agent header might reveal some OS information, but i wouldn't count on that.

For your use case i would do an ajax call using javascript from the client side to inform your server of the client's OS. And do it waterproof.

Here is an example.

Javascript (client side, browser detection + ajax call ):

window.addEvent('domready', function() { 
  if (BrowserDetect) { 
    var q_data = 'ajax=true&browser=' + BrowserDetect.browser + '&version=' + BrowserDetect.version + '&os=' + BrowserDetect.OS; 
    var query = 'record_browser.php' 
    var req = new Request.JSON({url: query, onComplete: setSelectWithJSON, data: q_data}).post(); 
  } 
}); 

PHP (server side):

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    $session = session_id(); 
    $user_id = isset($user_id) ? $user_id : 0; 
    $browser = isset($_POST['browser']) ? $_POST['browser'] : ''; 
    $version = isset($_POST['version']) ? $_POST['version'] : ''; 
    $os = isset($_POST['os']) ? $_POST['os'] : ''; 

    // now do here whatever you like with this information
} 
like image 23
Thariama Avatar answered Oct 17 '22 11:10

Thariama