Created
August 7, 2010 11:58
-
-
Save simonkberg/512736 to your computer and use it in GitHub Desktop.
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment