How to Detect Browser with PHP

One of the frequently asked questions while working with PHP is how to detect the browser.

In this short tutorial, we will show you the way of getting the browser easily with the PHP programming language arsenal.

In PHP, there is a global variable known as $_SERVER. This variable is mostly used for printing the server and the environment information.

Watch a course Learn object oriented PHP

Once you try printing $_SERVER['HTTP_USER_AGENT'], you will receive the information about the browser.

But note that, depending on the browser, the output can be different. To overcome such kind of issues, a specific code should be written.

So, for detecting the browser with PHP, you can use the getBrowser() function in the following way:

<?php

function getBrowser()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $browser = "N/A";

    $browsers = [
        '/msie/i' => 'Internet explorer',
        '/firefox/i' => 'Firefox',
        '/safari/i' => 'Safari',
        '/chrome/i' => 'Chrome',
        '/edge/i' => 'Edge',
        '/opera/i' => 'Opera',
        '/mobile/i' => 'Mobile browser',
    ];

    foreach ($browsers as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $browser = $value;
        }
    }

    return $browser;
}

echo "Browser: " . getBrowser();

?>

So, in this short tutorial, we represented to you how to detect the browser with PHP via writing a specific code. It will help to significantly increase your programming practice.