Post cover
Created 8 month back

Detecting browser types with PHP using the user agent

The simple code solutions for detect browser types using PHP

1. PHP has a get_browser() function by default, to determine the browser type, but currently it does not always work:

<?php

$browser = get_browser($_SERVER['HTTP_USER_AGENT']);

var_dump($browser);

2. A code solution created by GeekParty. With this code you can detect many popular browsers:

<?php

function get_browser_type() {
    $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

    if (!$user_agent) {
        return NULL;
    }

    $browser_types = [
        'wyzo/'                      => 'Wyzo',
        'arora/'                     => 'Arora',
        'chimera/'                   => 'Chimera',
        'ucbrowser/'                 => 'UC Browser',
        'dillo/'                     => 'Dillo',
        'dooble/'                    => 'Dooble',
        'opera mini/'                => 'Opera mini',
        'opera mobi/'                => 'Opera Mobile',
        'opr/'                       => 'Opera',
        'opera/'                     => 'Opera',
        'msie/'                      => 'Internet Explorer 10-',
        'trident/'                   => 'Internet Explorer 11',
        'america online browser 1.1' => 'America Online Browser 1.1',
        'amigavoyager/'              => 'AmigaVoyager',
        'yabrowser/'                 => 'Yandex Browser',
        'acoo browser'               => 'Acoo Browser',
        'seamonkey/'                 => 'Seamonkey',
        'edge/'                      => 'Microsoft Edge',
        'edgios/'                    => 'Microsoft Edge for iOS',
        'edg/'                       => 'Microsoft Edge (Chromium)',
        'blackberry'                 => 'BlackBerry',
        'chromium/'                  => 'Chromium',
        'crios/'                     => 'Chrome for iOS',
        'chrome/'                    => 'Chrome',
        'firefox/'                   => 'Firefox',
        'fxios/'                     => 'Firefox for iOS',
    ];

    $user_agent = strtolower($user_agent);

    // Find browser
    foreach ($browser_types as $browser_agent => $browser_type) {
        if (strpos($user_agent, $browser_agent) !== false) {
            return $browser_type;
        }
    }

    // Find Android Browsers
    if (preg_match('/android(.*?)version(.*?)mobile safari/', $user_agent)) {
        return 'Android Browser';
    }

    // Find Safari Browsers
    if (preg_match('/(ipad|iphone|macintosh)(.*)version\/(.*?)safari\//', $user_agent)) {
        return 'Safari';
    }

    return NULL;
}

if ($browser = get_browser_type()) {
    echo $browser;
} else {
    echo 'Browser not detected';
}