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 Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay