Come rilevare il sistema operativo con PHP

In questo tutorial imparerete come creare una funzione che permette di rilevare il sistema operativo partendo dall'user agent.

  1.  
  2. < ?php
  3.  
  4. $uagent = $_SERVER['HTTP_USER_AGENT'] . "<br/>";
  5.  
  6. function os_info($uagent)
  7. {
  8. // the order of this array is important
  9. global $uagent;
  10. $oses = array(
  11. 'Win311' => 'Win16',
  12. 'Win95' => '(Windows 95)|(Win95)|(Windows_95)',
  13. 'WinME' => '(Windows 98)|(Win 9x 4.90)|(Windows ME)',
  14. 'Win98' => '(Windows 98)|(Win98)',
  15. 'Win2000' => '(Windows NT 5.0)|(Windows 2000)',
  16. 'WinXP' => '(Windows NT 5.1)|(Windows XP)',
  17. 'WinServer2003' => '(Windows NT 5.2)',
  18. 'WinVista' => '(Windows NT 6.0)',
  19. 'Windows7' => '(Windows NT 6.1)',
  20. 'Windows8' => '(Windows NT 6.2)',
  21. 'WinNT' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
  22. 'OpenBSD' => 'OpenBSD',
  23. 'SunOS' => 'SunOS',
  24. 'Ubuntu' => 'Ubuntu',
  25. 'Android' => 'Android',
  26. 'Linux' => '(Linux)|(X11)',
  27. 'iPhone' => 'iPhone',
  28. 'iPad' => 'iPad',
  29. 'MacOS' => '(Mac_PowerPC)|(Macintosh)',
  30. 'QNX' => 'QNX',
  31. 'BeOS' => 'BeOS',
  32. 'OS2' => 'OS/2',
  33. 'SearchBot' => '(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'
  34. );
  35. $uagent = strtolower($uagent ? $uagent : $_SERVER['HTTP_USER_AGENT']);
  36. foreach ($oses as $os => $pattern)
  37. if (preg_match('/' . $pattern . '/i', $uagent))
  38. return $os;
  39. return 'Unknown';
  40. }
  41. echo os_info($uagent);
  42.  
  43. ?>
  44.