reliable user browser detection with php

There are several ways to detect a user's browser using PHP. One common method is to use the $_SERVER['HTTP_USER_AGENT'] variable, which contains information about the user's browser, such as its name and version.

You can use regular expressions to match this string against known patterns for different browsers. To fake the $_SERVER['HTTP_USER_AGENT'] variable in the example, you can simply assign a custom string to the $user_agent variable before running the code:

<?php
// in reality you would do $user_agent = $_SERVER['HTTP_USER_AGENT'];
$user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36";

$browser = "Unknown browser";

if (preg_match('/MSIE/i', $user_agent)) {
  $browser = 'Internet Explorer';
} elseif (preg_match('/Firefox/i', $user_agent)) {
  $browser = 'Mozilla Firefox';
} elseif (preg_match('/Chrome/i', $user_agent)) {
  $browser = 'Google Chrome';
} elseif (preg_match('/Safari/i', $user_agent)) {
  $browser = 'Apple Safari';
} elseif (preg_match('/Opera/i', $user_agent)) {
  $browser = 'Opera';
}

echo "Your browser is: " . $browser;
?>

Another way is to use the get_browser() function, which uses a browscap.ini file to match the user agent string. This method is more reliable than using regular expressions, but it requires the browscap.ini file to be up-to-date.

<?php

$browser = get_browser(null, true);
print_r($browser);

It is important to keep in mind that browser detection is not a 100% reliable way to determine the user's browser, as the user agent string can be easily spoofed.