DEV Community

loading...
Cover image for How to Detect Browser in PHP

How to Detect Browser in PHP

charlygarcia120 profile image Carlos Alberto ・1 min read

We will to write a function in PHP using $_SERVER['HTTP_USER_AGENT'] to detect the browser an d SO of the client

function detect() {
        $browser=array("SAFARI","CHROME","IE","EDGE","OPR","MOZILLA","NETSCAPE","FIREFOX");

        # default values for browser an SO
        $info['browser'] = "OTHER";
        $info['os'] = "OTHER";

        # search browser and SO
        foreach($browser as $parent)
        {
            $s = strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent);
            $f = $s + strlen($parent);

            $version = substr($_SERVER['HTTP_USER_AGENT'], $f, 15);
            $version = preg_replace('/[^0-9,.]/','',$version);
            if ($s)
            {
                $info['browser'] = $parent;
                $info['version'] = $version;
            }
        }
        return $info;
    }
Enter fullscreen mode Exit fullscreen mode

My wish is that you find usefull this function , and can be used in your programs to detect Browser and SO and show diferent pages , depending of your needs

Discussion (1)

pic
Editor guide
Collapse
lito profile image
Lito

You should escape . on version check expression:

$version = preg_replace('/[^0-9,\.]/', '', $version);
Enter fullscreen mode Exit fullscreen mode