How to detect browser in PHP?

Sometimes you need to detect a user’s browser from PHP for the purposes of displaying browser specific content or adjusting CSS & HTML.

PHP’s $_SERVER global variable holds browser’s ID information in HTTP_USER_AGENT key: $_SERVER['HTTP_USER_AGENT'].

<?php
$userAgent = $_SERVER['HTTP_USER_AGENT'];

if (preg_match('/MSIE/i', $user_agent)) {
    echo "Internet Explorer";
} else {
    echo "Non-IE Browser";
}

Better alternative would be also to use PHP function get_browser:

<?php
$browser = get_browser(null, true);
print_r($browser);

Libraries to check out when you need some advanced functionalities:

GitHub OctocatFound a typo? Something wrong with this content? Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all the contributors.