10

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
user435216
  • 305
  • 2
  • 5
  • 16
  • 1
    http://stackoverflow.com/questions/228256/operating-system-from-user-agent-http-header – user187291 Nov 05 '10 at 09:31
  • possible duplicate of [Get operating system info with PHP](http://stackoverflow.com/questions/18070154/get-operating-system-info-with-php) – T.Todua Nov 27 '14 at 10:30

3 Answers3

26
<?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;

?>
Ali Alnoaimi
  • 2,278
  • 2
  • 21
  • 31
6

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
} 
Thariama
  • 50,002
  • 13
  • 138
  • 166
  • Seems reliable. However I assume the detection only occurs after page load? – user435216 Nov 05 '10 at 09:38
  • Without page load you won't be able to retrieve more than what the user-agent header reveal. Well, you can save the users OS when initializing the session (on first page load), a workaround could be to do a redirect to a second page after you detected the os on the first page. – Thariama Nov 05 '10 at 09:43
0

use the Net_UserAgent package

docu is here: http://pear.php.net/package/Net_UserAgent_Detect/docs/latest/Net_UserAgent/Net_UserAgent_Detect.html#methodgetOSString

get the php file here: package/Net_UserAgent_Detect/docs/latest/__filesource/fsource_Net_UserAgent__Net_UserAgent_Detect-2.5.1Detect.php.html

rémy
  • 1,026
  • 13
  • 18