Php : Finding Chrome and Safari Browsers

◇◆丶佛笑我妖孽 提交于 2019-12-21 08:16:18

问题


I use below code to find user agent,

    $user_agent = $_SERVER['HTTP_USER_AGENT']; 
    if (preg_match('/MSIE/i', $user_agent)) { 
       echo "Internet Explorer";
    }
    if (preg_match('/Firefox/i', $user_agent)) { 
       echo "FireFox";
    }
    if (strpos( $user_agent, 'Chrome') !== false)
    {
        echo "Google Chrome";
    }
    if (strpos( $user_agent, 'Safari') !== false)
    {
       echo "Safari";
    }
    if (preg_match('/Opera/i', $user_agent)) { 
       echo "Opera";
    }

    ?>

But my chrome browser returning below useragent suddenly

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

It contains the word safari and chrome.so both the browser names are printed.what is the solution for this.thanks.


回答1:


Chrome's user agent contains Safari but Safari's user agent doesn't contain Chrome so use if ... elseif:

if (stripos( $user_agent, 'Chrome') !== false)
{
    echo "Google Chrome";
}

elseif (stripos( $user_agent, 'Safari') !== false)
{
   echo "Safari";
}

Note: use stripos instead of strpos to account for case-variations.




回答2:


Try this :

$browser = get_browser(null, true);
print_r($browser);

From doc : Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

ref: http://php.net/manual/en/function.get-browser.php



来源:https://stackoverflow.com/questions/15272084/php-finding-chrome-and-safari-browsers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!