User agent extracting OS and browser from a string

I would like to extract the full OS name and browser from the user agent string. How can i do this?

+4
source share
3 answers

It seems to me difficult to get the full name of the OS and the full name of the browser, since many browsers identify themselves differently. You probably need some kind of fancy regular expression, and then it might not even work in 100% of cases.

Here is a simple method that I use to identify the browser. You can adapt it to suit your needs.

<?php public static function getUserAgent() { static $agent = null; if ( empty($agent) ) { $agent = $_SERVER['HTTP_USER_AGENT']; if ( stripos($agent, 'Firefox') !== false ) { $agent = 'firefox'; } elseif ( stripos($agent, 'MSIE') !== false ) { $agent = 'ie'; } elseif ( stripos($agent, 'iPad') !== false ) { $agent = 'ipad'; } elseif ( stripos($agent, 'Android') !== false ) { $agent = 'android'; } elseif ( stripos($agent, 'Chrome') !== false ) { $agent = 'chrome'; } elseif ( stripos($agent, 'Safari') !== false ) { $agent = 'safari'; } elseif ( stripos($agent, 'AIR') !== false ) { $agent = 'air'; } elseif ( stripos($agent, 'Fluid') !== false ) { $agent = 'fluid'; } } return $agent; } 
+6
source

@augustknight: Note that IE11 does not send the "MSIE" token, I would suggest adding a match to the Trident token.

Example IE 11 User Agent:

 Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko 

change code:

 <?php public static function getUserAgent() { static $agent = null; if ( empty($agent) ) { $agent = $_SERVER['HTTP_USER_AGENT']; if ( stripos($agent, 'Firefox') !== false ) { $agent = 'firefox'; } elseif ( stripos($agent, 'MSIE') !== false ) { $agent = 'ie'; } elseif ( stripos($agent, 'Trident') !== false ) { $agent = 'ie'; } elseif ( stripos($agent, 'iPad') !== false ) { $agent = 'ipad'; } elseif ( stripos($agent, 'Android') !== false ) { $agent = 'android'; } elseif ( stripos($agent, 'Chrome') !== false ) { $agent = 'chrome'; } elseif ( stripos($agent, 'Safari') !== false ) { $agent = 'safari'; } elseif ( stripos($agent, 'AIR') !== false ) { $agent = 'air'; } elseif ( stripos($agent, 'Fluid') !== false ) { $agent = 'fluid'; } } return $agent; } 

? >

+2
source

PHP also has a built-in function to achieve this and more: get_browser() .

 $agent = get_browser(); echo $agent->platform; echo $agent->parent; // or $agent->browser . $agent->version 
+1
source

Source: https://habr.com/ru/post/1401268/


All Articles