How to get browser id in php?

I am looking a way to store unique ID of web browsers in PHP? I searched everywhere..but couldn't find any useful things. First of all, does web browsers have a unique ID or something like that to identify them??? Like the computers have a unique IP address, does browsers have anything like that?? I am trying this so that I can store user details into my database. So, we can find out a user used which browser to access my PHP website. Can I store such an ID to a php variable?

for example, $x= ID of the web browser.

zheek

7421 gold badge11 silver badges22 bronze badges

asked Jul 1, 2014 at 11:28

How to get browser id in php?

5

When a user visits your site you know his IP, browser, OS and other stuff. You need to know if the next time the same user visits you (same IP, same login perhaps) is using the same browser. This can be achieved in two ways:

a) Create a cookie, store it in the browser and in your DB, then compare every visitor that has that cookie against your existing cookie table to identify him. If the cookie has a very long expiration time it won't be lost across sessions, and will be unique to each browser. But it will be lost if the user clears cookies.

b) Store a string in the browser's local storage. This works pretty much the same as the cookie method but there's no expiration date for the data, and it's thougher to remove it than to clear cookies.

There are other methods, like combining different kind of cookies to provide redundancy. I remember a project called Evercookie that did something like that. I believe it's pretty much abandoned now.

answered Jul 1, 2014 at 11:36

ffflabsffflabs

16.7k5 gold badges52 silver badges76 bronze badges

You can use the browscap library and then make an md5 of the browser information:

Uses GaretJax/phpbrowscap

$bc = new \phpbrowscap\Browscap('data/');
$current_browser = $bc->getBrowser(null,true);
$str = json_encode($current_browser);
$browser_id = md5($str);

answered Feb 9, 2017 at 19:43

How to get browser id in php?

Isaac LimónIsaac Limón

1,83018 silver badges14 bronze badges

❮ PHP Misc Reference

Example

Look up the browscap.ini file and return the capabilities of the browser:

<?php
echo $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser();
print_r($browser);
?>

Try it Yourself »


Definition and Usage

The get_browser() function looks up the user's browscap.ini file and returns the capabilities of the user's browser.


Syntax

get_browser(user_agent,return_array)

Parameter Values

ParameterDescription
user_agent Optional. Specifies the name of an HTTP user agent. Default is the value of $HTTP_USER_AGENT. You can bypass this parameter with NULL
return_array Optional. If this parameter is set to TRUE, the function will return an array instead of an object

Technical Details

Return Value:Returns an object or an array with information about the user's browser on success, or FALSE on failure
PHP Version:4+
Changelog:The return_array parameter was added in PHP 4.3.2

❮ PHP Misc Reference


(PHP 4, PHP 5, PHP 7, PHP 8)

get_browserTells what the user's browser is capable of

Description

get_browser(?string $user_agent = null, bool $return_array = false): object|array|false

Parameters

user_agent

The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter.

You can bypass this parameter with a null value.

return_array

If set to true, this function will return an array instead of an object.

Return Values

The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; true/false values for features such as frames, JavaScript, and cookies; and so forth.

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.

Returns false when no information can be retrieved, such as when the browscap configuration setting in php.ini has not been set.

Examples

Example #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";$browser get_browser(nulltrue);
print_r($browser);
?>

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Notes

Note:

In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.

Francesco R

6 years ago

If you ONLY need a very fast and simple function to detect the browser name (update to May 2016):

<?phpfunction get_browser_name($user_agent)
{
    if (
strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
    elseif (
strpos($user_agent, 'Edge')) return 'Edge';
    elseif (
strpos($user_agent, 'Chrome')) return 'Chrome';
    elseif (
strpos($user_agent, 'Safari')) return 'Safari';
    elseif (
strpos($user_agent, 'Firefox')) return 'Firefox';
    elseif (
strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';

        return

'Other';
}
// Usage:echo get_browser_name($_SERVER['HTTP_USER_AGENT']);?>

This function also resolves the trouble with Edge (that contains in the user agent the string "Safari" and "Chrome"), with Chrome (contains the string "Safari") and IE11 (that do not contains 'MSIE' like all other IE versions).

Note that "strpos" is the fastest function to check a string (far better than "preg_match") and Opera + Edge + Chrome + Safari + Firefox + Internet Explorer are the most used browsers today (over 97%).

ruudrp at live dot nl

11 years ago

To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.

<?php
function getBrowser()
{
   
$u_agent = $_SERVER['HTTP_USER_AGENT'];
   
$bname = 'Unknown';
   
$platform = 'Unknown';
   
$version= "";//First get the platform?
   
if (preg_match('/linux/i', $u_agent)) {
       
$platform = 'linux';
    }
    elseif (
preg_match('/macintosh|mac os x/i', $u_agent)) {
       
$platform = 'mac';
    }
    elseif (
preg_match('/windows|win32/i', $u_agent)) {
       
$platform = 'windows';
    }
// Next get the name of the useragent yes seperately and for good reason
   
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
       
$bname = 'Internet Explorer';
       
$ub = "MSIE";
    }
    elseif(
preg_match('/Firefox/i',$u_agent))
    {
       
$bname = 'Mozilla Firefox';
       
$ub = "Firefox";
    }
    elseif(
preg_match('/Chrome/i',$u_agent))
    {
       
$bname = 'Google Chrome';
       
$ub = "Chrome";
    }
    elseif(
preg_match('/Safari/i',$u_agent))
    {
       
$bname = 'Apple Safari';
       
$ub = "Safari";
    }
    elseif(
preg_match('/Opera/i',$u_agent))
    {
       
$bname = 'Opera';
       
$ub = "Opera";
    }
    elseif(
preg_match('/Netscape/i',$u_agent))
    {
       
$bname = 'Netscape';
       
$ub = "Netscape";
    }
// finally get the correct version number
   
$known = array('Version', $ub, 'other');
   
$pattern = '#(?<browser>' . join('|', $known) .
   
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!
preg_match_all($pattern, $u_agent, $matches)) {
       
// we have no matching number just continue
   
}// see how many we have
   
$i = count($matches['browser']);
    if (
$i != 1) {
       
//we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
       
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
           
$version= $matches['version'][0];
        }
        else {
           
$version= $matches['version'][1];
        }
    }
    else {
       
$version= $matches['version'][0];
    }
// check if we have a number
   
if ($version==null || $version=="") {$version="?";}

        return array(

'userAgent' => $u_agent,
       
'name'      => $bname,
       
'version'   => $version,
       
'platform'  => $platform,
       
'pattern'    => $pattern
   
);
}
// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

Anonymous

3 years ago

Follow up to Francesco R's post from 2016.

His function works for most human traffic; added a few lines to cover the most common bot traffic. Also fixed issue with function failing to detect strings at position 0 due to strpos behavior.

<?php
// Function written and tested December, 2018
function get_browser_name($user_agent)
{
       
// Make case insensitive.
       
$t = strtolower($user_agent);// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
        // "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
        //     http://php.net/manual/en/function.strpos.php
       
$t = " " . $t;// Humans / Regular Users     
       
if     (strpos($t, 'opera'     ) || strpos($t, 'opr/')     ) return 'Opera'            ;
        elseif (
strpos($t, 'edge'      )                           ) return 'Edge'             ;
        elseif (
strpos($t, 'chrome'    )                           ) return 'Chrome'           ;
        elseif (
strpos($t, 'safari'    )                           ) return 'Safari'           ;
        elseif (
strpos($t, 'firefox'   )                           ) return 'Firefox'          ;
        elseif (
strpos($t, 'msie'      ) || strpos($t, 'trident/7')) return 'Internet Explorer';// Search Engines 
       
elseif (strpos($t, 'google'    )                           ) return '[Bot] Googlebot'   ;
        elseif (
strpos($t, 'bing'      )                           ) return '[Bot] Bingbot'     ;
        elseif (
strpos($t, 'slurp'     )                           ) return '[Bot] Yahoo! Slurp';
        elseif (
strpos($t, 'duckduckgo')                           ) return '[Bot] DuckDuckBot' ;
        elseif (
strpos($t, 'baidu'     )                           ) return '[Bot] Baidu'       ;
        elseif (
strpos($t, 'yandex'    )                           ) return '[Bot] Yandex'      ;
        elseif (
strpos($t, 'sogou'     )                           ) return '[Bot] Sogou'       ;
        elseif (
strpos($t, 'exabot'    )                           ) return '[Bot] Exabot'      ;
        elseif (
strpos($t, 'msn'       )                           ) return '[Bot] MSN'         ;// Common Tools and Bots
       
elseif (strpos($t, 'mj12bot'   )                           ) return '[Bot] Majestic'     ;
        elseif (
strpos($t, 'ahrefs'    )                           ) return '[Bot] Ahrefs'       ;
        elseif (
strpos($t, 'semrush'   )                           ) return '[Bot] SEMRush'      ;
        elseif (
strpos($t, 'rogerbot'  ) || strpos($t, 'dotbot')   ) return '[Bot] Moz or OpenSiteExplorer';
        elseif (
strpos($t, 'frog'      ) || strpos($t, 'screaming')) return '[Bot] Screaming Frog';// Miscellaneous
       
elseif (strpos($t, 'facebook'  )                           ) return '[Bot] Facebook'     ;
        elseif (
strpos($t, 'pinterest' )                           ) return '[Bot] Pinterest'    ;// Check for strings commonly used in bot user agents  
       
elseif (strpos($t, 'crawler' ) || strpos($t, 'api'    ) ||
               
strpos($t, 'spider'  ) || strpos($t, 'http'   ) ||
               
strpos($t, 'bot'     ) || strpos($t, 'archive') ||
               
strpos($t, 'info'    ) || strpos($t, 'data'   )    ) return '[Bot] Other'   ;

                return

'Other (Unknown)';
}
?>
Post with more depth here:
https://www.256kilobytes.com/content/show/1922/how-to-parse-a-user-agent-in-php-with-minimal-effort

The Digital Orchard

5 years ago

Good news! The latest version of PHP has a performance fix for this function. It's reportedly now 100x faster. See the ChangeLog for specifics.

Jeff Williams

4 years ago

To automatically update your browscap.ini file on linux servers, you can use this simple shell script:

wget -O /etc/browscap.ini "http://browscap.org/stream?q=Full_PHP_BrowsCapINI"
chmod 664 /etc/browscap.ini

You can put it in the weekly cron job folder usually located in /etc/cron.weekly just don't forget to make the script executable (chmod 775 scriptname).

mike at mike-griffiths dot co dot uk

15 years ago

You should not rely on just this for cross-browser compatibility issues.  Good practice would be to include HTML if-statements for IE stylesheets as well as dynamically checking the browser type.

tim at digicol dot de

8 years ago

Be aware that loading php_browscap.ini via the browscap php.ini setting may consume a non-trivial amount of memory. Current versions are several MB in size (even the “lite” one) and can eat tens of MB of RAM in each PHP process. This happens even if you never call get_browser() since php_browscap.ini is loaded when PHP is starting up.

Make sure to leave the browscap php.ini setting empty if you don’t use get_browser() – maybe you only call it only from PHP Web pages, but not from PHP CLI code.

I’d recommend comparing your processes’ memory consumption with and without php_browscap.ini being loaded. If necesseray, consider creating your own stripped-down copy of php_browscap.ini with just the browsers that are important to you.

shashank

7 years ago

As ruudrp had given the code http://php.net/manual/en/function.get-browser.php#101125, I have added code for Internet Explorer 11

<?php
function getBrowser()
{
   
$u_agent = $_SERVER['HTTP_USER_AGENT'];
   
$bname = 'Unknown';
   
$platform = 'Unknown';
   
$version= "";//First get the platform?
   
if (preg_match('/linux/i', $u_agent)) {
       
$platform = 'linux';
    }
    elseif (
preg_match('/macintosh|mac os x/i', $u_agent)) {
       
$platform = 'mac';
    }
    elseif (
preg_match('/windows|win32/i', $u_agent)) {
       
$platform = 'windows';
    }
// Next get the name of the useragent yes seperately and for good reason
   
if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
       
$bname = 'Internet Explorer';
       
$ub = "MSIE";
    }
    elseif(
preg_match('/Trident/i',$u_agent))
    {
// this condition is for IE11
       
$bname = 'Internet Explorer';
       
$ub = "rv";
    }
    elseif(
preg_match('/Firefox/i',$u_agent))
    {
       
$bname = 'Mozilla Firefox';
       
$ub = "Firefox";
    }
    elseif(
preg_match('/Chrome/i',$u_agent))
    {
       
$bname = 'Google Chrome';
       
$ub = "Chrome";
    }
    elseif(
preg_match('/Safari/i',$u_agent))
    {
       
$bname = 'Apple Safari';
       
$ub = "Safari";
    }
    elseif(
preg_match('/Opera/i',$u_agent))
    {
       
$bname = 'Opera';
       
$ub = "Opera";
    }
    elseif(
preg_match('/Netscape/i',$u_agent))
    {
       
$bname = 'Netscape';
       
$ub = "Netscape";
    }
// finally get the correct version number
    // Added "|:"
   
$known = array('Version', $ub, 'other');
   
$pattern = '#(?<browser>' . join('|', $known) .
    
')[/|: ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!
preg_match_all($pattern, $u_agent, $matches)) {
       
// we have no matching number just continue
   
}// see how many we have
   
$i = count($matches['browser']);
    if (
$i != 1) {
       
//we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
       
if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
           
$version= $matches['version'][0];
        }
        else {
           
$version= $matches['version'][1];
        }
    }
    else {
       
$version= $matches['version'][0];
    }
// check if we have a number
   
if ($version==null || $version=="") {$version="?";}

    return array(

'userAgent' => $u_agent,
       
'name'      => $bname,
       
'version'   => $version,
       
'platform'  => $platform,
       
'pattern'    => $pattern
   
);
}
// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

tom at tgibbons dot com

7 months ago

PHP cron script to automatically update browscap.ini. It compares version numbers to determine if update is needed:

<?php
       $eol
="\r\n";                           //set end of line - cron$fileurl = "https://browscap.org/stream?q=PHP_BrowsCapINI";
      
$verurl = "https://browscap.org/version-number";
      
$file = "/path/to/browscap.ini";//Find current version
      
$fp = fopen($file, "r+");
       while ((
$line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
           if(
strpos($line,"Version=")===0) {
               list(
$temp, $curver) = explode("=",$line);
               break;
           }
       }
      
fclose($fp);
       echo(
"Current browscap.ini file version: " . $curver);
      
//Get browscap.org current version
      
$newver = file_get_contents($verurl);
       echo(
$eol . "New browscap.ini file version: " . $newver);
      
//Update if new version available
      
if($newver > $curver) {
           if(
file_put_contents($file, file_get_contents($fileurl))) {
               echo(
$eol . "browscap.ini has been updated!");
           }
           else {
               echo(
$eol . "browscap.ini update failed!");
           }
       }
       else {
           echo(
$eol . "browscap.ini is up to date!");
       }
       echo(
$eol . "End of Cron job." . $eol");
?>

max at phpexpert dot de

18 years ago

Be aware of the fact that this function shows what a specific browser might be able to show, but NOT what the user has turned on/off.

So maybe this function tells you that the browser is abel to to javascript even when javascript is turned off by the user.

jeremie dot legrand at komori-chambon dot fr

6 years ago

Be careful if you use the "Full" Browscap INI file in your php.ini config: I wondered why each Apache thread took 350MB RAM on my server until I changed the "Full" version by the "Lite" one (45MB to 0.7MB)

Now, each thread takes only 16MB...
So if it is enough for you, use the Lite version!

zed

6 years ago

To complete Francesco R, I added the version of the navigator :

function getNavigateur($user_agent)
    {

        if(empty($user_agent)) {
            return array('nav' => 'NC', 'name' => 'NC', 'version' => 'NC');
        }

        $content_nav['name'] = 'Unknown';

        if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) {

            $content_nav['name'] = 'Opera';

            if (strpos($user_agent, 'OPR/')) {
                $content_nav['reel_name'] = 'OPR/';
            } else {
                $content_nav['reel_name'] = 'Opera';
            }

        }
        elseif (strpos($user_agent, 'Edge')) {
            $content_nav['name'] = $content_nav['reel_name'] = 'Edge';
        }
        elseif (strpos($user_agent, 'Chrome')) $content_nav['name'] = $content_nav['reel_name'] = 'Chrome';
        elseif (strpos($user_agent, 'Safari')) $content_nav['name'] = $content_nav['reel_name'] = 'Safari';
        elseif (strpos($user_agent, 'Firefox')) $content_nav['name'] = $content_nav['reel_name'] = 'Firefox';
        elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7') || strpos($user_agent, 'Trident/7.0; rv:')) {
            $content_nav['name'] = 'Internet Explorer';

            if (strpos($user_agent, 'Trident/7.0; rv:')) {
                $content_nav['reel_name'] = 'Trident/7.0; rv:';
            } elseif (strpos($user_agent, 'Trident/7')) {
                $content_nav['reel_name'] = 'Trident/7';
            } else {
                $content_nav['reel_name'] = 'Opera';
            }

        }

        $pattern = '#' . $content_nav['reel_name'] . '\/*([0-9\.]*)#';

        $matches = array();

        if(preg_match($pattern, $user_agent, $matches)) {

            $content_nav['version'] = $matches[1];
            return $content_nav;

        }

        return array('name' => $content_nav['name'], 'version' => 'Inconnu');
    }

p2 at eduardoruiz dot es

6 years ago

BE CAREFUL WITH THIS FUNCTION!!
This function uses a lot of CPU and RAM on the whole server resources.
Perhaps if you use this function a few times then no problem, but NOT if you use at any page request, or once per session.

Also, this function doesn't work correctly and may returns wrong values, wildcards or empty, so it's not very useful for web statistics.

The best way is to use preg_match for detect browser/platform.

Which function is used to get Http_user_agent values *?

PHP get_browser() Function echo $_SERVER['HTTP_USER_AGENT'];

Which browser is best for PHP?

Chrome, for instance, one of more adopted and fast browsers, has a good response over PHP, just for it, for being one of the fastest nowadays (I use Firefox, but much Benchmark software point Google browser in advantage).

What is a Web browser in Java?

web Browser is an application software that allows us to view and explore information on the web. User can request for any web page by just entering a URL into address bar. Web browser can show text, audio, video, animation and more.