W3docs

How to Detect Browser with PHP

Browser detection is used to determine the web browser a visitor is using and to serve browser-appropriate content to the visitor. Know how to do it with PHP.

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

In this short tutorial, we will show you how to detect the browser using PHP.

In PHP, the $_SERVER superglobal contains server and environment information.

Accessing <kbd class="highlighted">$_SERVER['HTTP_USER_AGENT']</kbd> returns a string that identifies the browser and operating system.

User-agent strings vary widely across browsers and versions. To parse them reliably, you can use a custom function like the following:

<?php

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

    $browsers = [
        '/Edg\//i' => 'Edge',
        '/Chrome\//i' => 'Chrome',
        '/Safari\//i' => 'Safari',
        '/Firefox\//i' => 'Firefox',
        '/OPR\//i' => 'Opera',
        '/Mobile/i' => 'Mobile browser',
    ];

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

    return $browser;
}

echo "Browser: " . getBrowser();

?>

This example demonstrates basic browser detection using a custom function. For production applications, note that PHP's built-in get_browser() requires the browscap extension, which is rarely enabled by default. Instead, consider using a dedicated parsing library like mobiledetect/mobiledetect for reliable results.