DEV Community

Cover image for How to Detect Browser in PHP
Carlos Alberto
Carlos Alberto

Posted on

2

How to Detect Browser in PHP

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

Top comments (1)

Collapse
 
lito profile image
Lito β€’

You should escape . on version check expression:

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

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more