pTutorial

New way to learn PHP Example

How To Detect Browser in PHP

Browser detection

To detect our client browser use server super global array. Let us see the example of browser detection.

Browser detection example

<?php

$detail  = $_SERVER['HTTP_USER_AGENT'];

function browser() 
{
    global $detail;

    $browser = "Error occur";

$brows_a =  array
(
'/safari/i'     =>  'Safari',
'/firefox/i'    =>  'Mogilla Firefox',
'/msie/i'       =>  'Internet Explorer',
'/chrome/i'     =>  'Google Chrome',
'/opera/i'      =>  'Opera',
'/netscape/i'   =>  'Netscape',
'/maxthon/i'    =>  'Maxthon',
'/konqueror/i'  =>  'Konqueror',
'/mobile/i'     =>  'Handheld Browser'
);

foreach ($brows_a as $key => $value) 
{ 
if (preg_match($key, $detail)) {
$browser = $value;
}
}
    return $browser;
}


$user_browser = browser();
echo "Browser:" .$user_browser;


?>

Explanation

In this example User-Agent information stored in the variable $detail. (Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page.)

Example: Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:33.0) Gecko/20100101 Firefox/33.0WINNT

Create a function and in the function create a variable and store the string like, not found or error and then create an array and store key and value like that.

In this function create a foreach loop and check the $detail variable to the given array and assign the browser at last call browser function in a variable and print this variable.

$_SERVER super global array

<?php

echo("
".$_SERVER['HTTP_USER_AGENT'].""); ?>

Explanation

In this example, we use server variable to print all the details like running operating system, browser etc.


QUOTES OF THE DAY

Eat to live, and not live for eat.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER