Write a simple PHP browser detection script

Web browse: A web browser is a software application for accessing information on the World Wide Web. Each individual web page, image, and video is identified by a distinct URL. These URLs, enable browsers to retrieve and display them on the user's device. A web browser is not the same thing as a search engine, though the two are often confused. For a user, a search engine is just a website, such as google.com, that stores searchable data about other websites. But in order to connect to and display websites on their device, a user needs to have a web browser installed.

Example 1:-

<?php echo "Your User Agent is :" . $_SERVER ['HTTP_USER_AGENT']; ?>
output:-
Your-User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36
example 2:-

<?php
$agent = $_SERVER["HTTP_USER_AGENT"];

if( preg_match('/MSIE (\d+\.\d+);/', $agent) ) {
  echo "You're using Internet Explorer";
} else if (preg_match('/Chrome[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Chrome";
} else if (preg_match('/Edge\/\d+/', $agent) ) {
  echo "You're using Edge";
} else if ( preg_match('/Firefox[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Firefox";
} else if ( preg_match('/OPR[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Opera";
} else if (preg_match('/Safari[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Safari";
}
?>
output:-
You're using Chrome
example 3:-

<?php
function getBrowser() {

$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = "N/A";

$browsers = array(
'/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();
?>
output :-
Browser: Chrome

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post