public
Last active

This PHP function detects which Browser (+version) and OS a user is running and returns or print it in a class-friendly format to use in e.g. Body-class

  • Download Gist
OS-Browser_classes.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
<?php
 
//
// This PHP function detects which Browser (+version) and OS a user is running and returns or
// print it in a class-friendly format to use in e.g. Body-class
//
// Use like <?php echo "<body class=\"".OSbodyClass(false)."\">"; ?>
// or <body class="<?php OSbodyClass(); ?>">
//
// example output for Firefox 3.6.8 running on Windows 7: <body class="windows firefox ff3">
//
 
function OSbodyClass($print = true) {
$browser = $_SERVER[ 'HTTP_USER_AGENT' ];
 
// Mac, PC ...or Linux
if ( preg_match( "/Mac/", $browser ) ){
$c[] = 'mac';
 
} elseif ( preg_match( "/Windows/", $browser ) ){
$c[] = 'windows';
 
} elseif ( preg_match( "/Linux/", $browser ) ) {
$c[] = 'linux';
 
} else {
$c[] = 'unknown-os';
}
 
// Checks browsers in this order: Chrome, Safari, Opera, MSIE, FF
if ( preg_match( "/Chrome/", $browser ) ) {
$c[] = 'chrome';
 
preg_match( "/Chrome\/(\d.\d)/si", $browser, $matches);
$ch_version = 'ch' . str_replace( '.', '-', $matches[1] );
$c[] = $ch_version;
 
} elseif ( preg_match( "/Safari/", $browser ) ) {
$c[] = 'safari';
preg_match( "/Version\/(\d.\d)/si", $browser, $matches);
$sf_version = 'sf' . str_replace( '.', '-', $matches[1] );
$c[] = $sf_version;
} elseif ( preg_match( "/Opera/", $browser ) ) {
$c[] = 'opera';
preg_match( "/Opera\/(\d.\d)/si", $browser, $matches);
$op_version = 'op' . str_replace( '.', '-', $matches[1] );
$c[] = $op_version;
} elseif ( preg_match( "/MSIE/", $browser ) ) {
$c[] = 'msie';
if( preg_match( "/MSIE 6.0/", $browser ) ) {
$c[] = 'ie6';
} elseif ( preg_match( "/MSIE 7.0/", $browser ) ){
$c[] = 'ie7';
} elseif ( preg_match( "/MSIE 8.0/", $browser ) ){
$c[] = 'ie8';
}
} elseif ( preg_match( "/Firefox/", $browser ) && preg_match( "/Gecko/", $browser ) ) {
$c[] = 'firefox';
preg_match( "/Firefox\/(\d)/si", $browser, $matches);
$ff_version = 'ff' . str_replace( '.', '-', $matches[1] );
$c[] = $ff_version;
} else {
$c[] = 'unknown-browser';
}
// Separates classes with a single space
$c = join(' ', $c);
 
// And tada!
return $print ? print($c) : $c;
} ?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.