php to detect browser

sam picture sam · Mar 14, 2013 · Viewed 43.3k times · Source

Ive got an odd css fault that i cant seem to fix, its only occuring in safari, not chrome so webkit targeting wont help.. what i was trying to do is set a block of php to check if the browsers safari, if so echo a peice of css.

So far ive got this (bellow) - Which works, but its also outputting the echo statement in chrome, any idea were ive gone wrong ?

<?php 

    if(isset($_SERVER['HTTP_USER_AGENT'])){
         $agent = $_SERVER['HTTP_USER_AGENT'];
    }

    if(strlen(strstr($agent,"Safari")) > 0 ){
        $browser = 'safari';
    }
    if($browser=='safari'){
        echo '<style>p {font-weight: 300;}</style>';
    }

?>

Ive just been playing arround with echo $_SERVER["HTTP_USER_AGENT"]; and this is what i get from safari

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17

and from chrome

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22

So it can tell its different browsers, but its obviously reading them both as Apple Web Kit, rather than safari or chrome. My php is a bit rusty how would i get it to target the safari user agent specificly ?

Answer

wicketyjarjar picture wicketyjarjar · Jun 12, 2013

Here is a more general solution based on po228's answer. I think it is easier to search directly for the version number of the browser, rather than the build number.

$ua = $_SERVER["HTTP_USER_AGENT"];      // Get user-agent of browser

$safariorchrome = strpos($ua, 'Safari') ? true : false;     // Browser is either Safari or Chrome (since Chrome User-Agent includes the word 'Safari')
$chrome = strpos($ua, 'Chrome') ? true : false;             // Browser is Chrome

if($safariorchrome == true AND $chrome == false){ $safari = true; }     // Browser should be Safari, because there is no 'Chrome' in the User-Agent

// Check for version numbers 
$v1 = strpos($ua, 'Version/1.') ? true : false;
$v2 = strpos($ua, 'Version/2.') ? true : false;
$v3 = strpos($ua, 'Version/3.') ? true : false;
$v4 = strpos($ua, 'Version/4.') ? true : false;
$v5 = strpos($ua, 'Version/5.') ? true : false;
$v6 = strpos($ua, 'Version/6.') ? true : false;

// Test versions of Safari
if($safari AND $v1){ echo 'Safari Version 1'; }
else if($safari AND $v2){ echo 'Safari Version 2'; }
else if($safari AND $v3){ echo 'Safari Version 3'; }
else if($safari AND $v4){ echo 'Safari Version 4'; }
else if($safari AND $v5){ echo 'Safari Version 5'; }
else if($safari AND $v6){ echo 'Safari Version 6'; }
else if($safari){ echo 'Safari newer than Version 6'; }
else{ echo "Not Safari"; }