downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

__halt_compiler> <exit
Last updated: Fri, 06 Nov 2009

view this page in

get_browser

(PHP 4, PHP 5)

get_browser Diz o que o browser do usuário pode fazer

Descrição

object get_browser ([ string $user_agent ] )

get_browser() tenta determinar as capacidades do browser do usuário. Isto é feito procurando a informação do browser no arquivo browscap.ini. Por padrão, o valor de $_SERVER["HTTP_USER_AGENT"] é usado; em qualquer caso você pode alterar isto (ex., procurar informação de outro browser) passando o parâmetro opcional user_agent para a função get_browser().

A informação é retornada como um objeto, que contém vários elementos com dados representando, por exemplo, os números de versão maior e menor, a string de ID, valores TRUE/FALSE para coisas como frames, JavaScript, e cookies; e assim em diante.

Enquanto browscap.ini contém informações sobre vários browser, ele precisa de atualizações para manter o banco de dados atual. O formato do arquivo é auto-explicatório.

O exemplo a seguir irá mostrar uma possível lista de toda a informação disponível sobre o browser do usuário.

Exemplo #1 Exemplo get_browser()

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";
$browser get_browser();
foreach (
$browser as $name => $value) {
    echo 
"<b>$name</b> $value <br />\n";
}
?>

A saída do script acima deve ser algo como isto:

Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr />
<b>browser_name_pattern:</b> Mozilla/4\.5.*<br />
<b>parent:</b> Netscape 4.0<br />
<b>platform:</b> Linux<br />
<b>majorver:</b> 4<br />
<b>minorver:</b> 5<br />
<b>browser:</b> Netscape<br />
<b>version:</b> 4<br />
<b>frames:</b> 1<br />
<b>tables:</b> 1<br />
<b>cookies:</b> 1<br />
<b>backgroundsounds:</b> <br />
<b>vbscript:</b> <br />
<b>javascript:</b> 1<br />
<b>javaapplets:</b> 1<br />
<b>activexcontrols:</b> <br />
<b>beta:</b> <br />
<b>crawler:</b> <br />
<b>authenticodeupdate:</b> <br />
<b>msn:</b> <br />

Para que isto funcione, sua configuração do browscap no php.ini deve apontar para o local correto do arquivo browscap.ini no seu sistema. browscap.ini não vem com o PHP mas você deve encontrar uma versão atualizada » do arquivo browscap.ini. Por padrão,a diretiva browscap esta comentada.

Os valores de cookies simplesmente indicam que que o browser é capaz de receber cookies e não indica que o usuário permite ao browser receber ou não cookies. O unico meio de testar se os cookies são aceitos é criar um com setcookie(), recarregar, e conferir o valor.

Nota: Em versões anteriores ao PHP 4.0.6, você tem que passar o user agent via o parâmetro opcional user_agent se a diretiva do PHP register_globals esta em off. Neste caso, você irá passar $HTTP_SERVER_VARS['HTTP_USER_AGENT'].



__halt_compiler> <exit
Last updated: Fri, 06 Nov 2009
 
add a note add a note User Contributed Notes
get_browser
Anonymous
10-Aug-2009 05:20
Browser and Version look like they need ?P<name>

i.e.
$pattern = '#(?P<browser>' . join('|', $known) . ')[/ ]+(?P<version>[0-9]+(?:\.[0-9]+)?)#';
robert at broofa dot com
18-Jul-2009 06:33
If you're just finding this API, note that you may want to use a lighter-weight
browser detection script.  get_browser() requires the "browscap.ini" file,
which is 300KB+.  Loading and processing this file will likely impact script
performance.  Although it surely provides excellent detection results, in most
cases a much simpler method can be just as effective.  This is why so many
previous commenters have provided alternate implementations.

Here's the solution I ended up using, which I've tested on the agents listed at
http://whatsmyuseragent.com/CommonUserAgents.asp It has the advantage of being
compact and reasonably easy to extend (just add entries to the $known array
defined at the top).  It should be fairly performant as well, since it doesn't
do any iteratoin or recursion.

<?php
function browser_info($agent=null) {
 
// Declare known browsers to look for
 
$known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape',
   
'konqueror', 'gecko');

 
// Clean up agent and build regex that matches phrases for known browsers
  // (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
  // version numbers.  E.g. "2.0.0.6" is parsed as simply "2.0"
 
$agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
 
$pattern = '#(?<browser>' . join('|', $known) .
   
')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)#';

 
// Find all phrases (or return empty array if none found)
 
if (!preg_match_all($pattern, $agent, $matches)) return array();

 
// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
  // Opera 7,8 have a MSIE phrase), use the last one found (the right-most one
  // in the UA).  That's usually the most correct.
 
$i = count($matches['browser'])-1;
  return array(
$matches['browser'][$i] => $matches['version'][$i]);
}
?>
This returns an array with the detected browser as the key, and the version as
the value, and also sets 'browser' and 'version' keys.  For example on Firefox
3.5:
<?php
$ua
= browser_info();
print_r($ua);
/* Yields ...
Array
(
    [firefox] => 3.5
    [browser] => firefox
    [version] => 3.5
)
*/

// Various browser tests you can do with the returned array ...
if ($ua['firefox']) ... // true
if ($ua['firefox'] > 3) ... // true
if ($ua['firefox'] > 4) ... // false
if ($ua['browser'] == 'firefox') ... // true
if ($ua['version'] > 3.5) ... // true
if ($ua['msie']) ... // false ('msie' key not defined)
if ($ua['opera'] > 3) ... // false ('opera' key not defined)
if ($ua['safari'] < 3) ... // false also ('safari' key not defined)
?>
Steve Perkins
21-Jun-2009 09:11
This is a simple class to detect the client browser and version using regular expressions.

<?PHP
class Browser
{
    private
$props    = array("Version" => "0.0.0",
                               
"Name" => "unknown",
                               
"Agent" => "unknown") ;

    public function
__Construct()
    {
       
$browsers = array("firefox", "msie", "opera", "chrome", "safari",
                           
"mozilla", "seamonkey",    "konqueror", "netscape",
                           
"gecko", "navigator", "mosaic", "lynx", "amaya",
                           
"omniweb", "avant", "camino", "flock", "aol");

       
$this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach(
$browsers as $browser)
        {
            if (
preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
               
$this->Name = $match[1] ;
               
$this->Version = $match[2] ;
                break ;
            }
        }
    }

    public function
__Get($name)
    {
        if (!
array_key_exists($name, $this->props))
        {
            die
"No such property or function $name)" ;
        }
        return
$this->props[$name] ;
    }

    public function
__Set($name, $val)
    {
        if (!
array_key_exists($name, $this->props))
        {
           
SimpleError("No such property or function.", "Failed to set $name", $this->props) ;
            die ;
        }
       
$this->props[$name] = $val ;
    }

}

?>

example code
<?PHP
$browser
= new Browser ;
echo
"$Browser->Name $Browser->Version" ;
?>
result when client using Firefox 3.0.11
firefox 3.0.11

result when client using unknown browser
unknown 0.0.0
 
etc etc
Steve Perkins
21-Jun-2009 02:42
This is a simple class to detect the client browser and version using regular expressions.

<?PHP
class Browser extends BaseObjects_PropertyArray
{
    private
$props    = array("Version" => "0.0.0",
                               
"Name" => "unknown",
                               
"Agent" => "unknown",
                               
"AllowsHeaderRedirect" => true) ;

    public function
__Construct()
    {
       
$browsers = array("firefox", "msie", "opera", "chrome", "safari",
                           
"mozilla", "seamonkey",    "konqueror", "netscape",
                           
"gecko", "navigator", "mosaic", "lynx", "amaya",
                           
"omniweb", "avant", "camino", "flock", "aol");

       
$this->Agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        foreach(
$browsers as $browser)
        {
            if (
preg_match("#($browser)[/ ]?([0-9.]*)#", $this->Agent, $match))
            {
               
$this->Name = $match[1] ;
               
$this->Version = $match[2] ;
                break ;
            }
        }
       
$this->AllowsHeaderRedirect = !($this->Name == "msie" && $this->Version < 7) ;
    }

    public function
__Get($name)
    {
        if (!
array_key_exists($name, $this->props))
        {
            die
"No such property or function $name)" ;
        }
        return
$this->props[$name] ;
    }

}

?>

example code
<?PHP
$browser
= new Browser ;
echo
"$Browser->Name $Browser->Version" ;
?>
result when client using Firefox 3.0.11
firefox 3.0.11

result when client using unknown browser
unknown 0.0.0
 
etc etc
Mattkun Koder
28-Apr-2009 12:00
If you want to use: ceo /a/ mmg5 /./ com 's improved version and STILL detect Google Chrome you need to move CHROME earlier on the list Before Safari otherwise it will be detected as safari.

    $browser_list = 'msie firefox chrome konqueror safari netscape navigator opera mosaic lynx amaya omniweb avant camino flock seamonkey aol mozilla gecko';
ceo /a/ mmg5 /./ com
05-Mar-2009 02:02
Here is an improved version of admin at studio-gepard dot pl.
This code supports: minor versions, checking or return browser data and more browsers like Chrome, Flock and others and version compare.

<?php

function w($a = '')
{
    if (empty(
$a)) return array();
   
    return
explode(' ', $a);
}

function
_browser($a_browser = false, $a_version = false, $name = false)
{
   
$browser_list = 'msie firefox konqueror safari netscape navigator opera mosaic lynx amaya omniweb chrome avant camino flock seamonkey aol mozilla gecko';
   
$user_browser = strtolower($_SERVER['HTTP_USER_AGENT']);
   
$this_version = $this_browser = '';
   
   
$browser_limit = strlen($user_browser);
    foreach (
w($browser_list) as $row)
    {
       
$row = ($a_browser !== false) ? $a_browser : $row;
       
$n = stristr($user_browser, $row);
        if (!
$n || !empty($this_browser)) continue;
       
       
$this_browser = $row;
       
$j = strpos($user_browser, $row) + strlen($row) + 1;
        for (;
$j <= $browser_limit; $j++)
        {
           
$s = trim(substr($user_browser, $j, 1));
           
$this_version .= $s;
           
            if (
$s === '') break;
        }
    }
   
    if (
$a_browser !== false)
    {
       
$ret = false;
        if (
strtolower($a_browser) == $this_browser)
        {
           
$ret = true;
           
            if (
$a_version !== false && !empty($this_version))
            {
               
$a_sign = explode(' ', $a_version);
                if (
version_compare($this_version, $a_sign[1], $a_sign[0]) === false)
                {
                   
$ret = false;
                }
            }
        }
       
        return
$ret;
    }
   
   
//
   
$this_platform = '';
    if (
strpos($user_browser, 'linux'))
    {
       
$this_platform = 'linux';
    }
    elseif (
strpos($user_browser, 'macintosh') || strpos($user_browser, 'mac platform x'))
    {
       
$this_platform = 'mac';
    }
    else if (
strpos($user_browser, 'windows') || strpos($user_browser, 'win32'))
    {
       
$this_platform = 'windows';
    }
   
    if (
$name !== false)
    {
        return
$this_browser . ' ' . $this_version;
    }
   
    return array(
       
"browser"      => $this_browser,
       
"version"      => $this_version,
       
"platform"     => $this_platform,
       
"useragent"    => $user_browser
   
);
}

// Examples

echo '<pre>';
print_r(_browser()); // return array of browser data

var_dump(_browser('firefox')); // return true if using firefox
var_dump(_browser('msie', '>= 7.0')); // return true if using IE 7.0 or above else false
var_dump(_browser('firefox', '< 3.0.5')); // return true if using below firefox 3.0.5 (can check minor version)
var_dump(_browser(false, false, true)); // return string of name of browser and version

// To check if Gecko browser is used
var_dump(_browser('gecko'));

// version_compared function is used so you can use the same operator syntax
var_dump(_browser('firefox', 'le 1.5'));

echo
'</pre>';

?>
Daniel Frechette
16-Feb-2009 10:40
A newer version for those only interested in identifying A-grade browsers. The code was ported in part from JQuery 1.3.1.

<?php
class Browser {
   
/**
        Figure out what browser is used, its version and the platform it is
        running on.

        The following code was ported in part from JQuery v1.3.1
    */
   
public static function detect() {
       
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

       
// Identify the browser. Check Opera and Safari first in case of spoof. Let Google Chrome be identified as Safari.
       
if (preg_match('/opera/', $userAgent)) {
           
$name = 'opera';
        }
        elseif (
preg_match('/webkit/', $userAgent)) {
           
$name = 'safari';
        }
        elseif (
preg_match('/msie/', $userAgent)) {
           
$name = 'msie';
        }
        elseif (
preg_match('/mozilla/', $userAgent) && !preg_match('/compatible/', $userAgent)) {
           
$name = 'mozilla';
        }
        else {
           
$name = 'unrecognized';
        }

       
// What version?
       
if (preg_match('/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/', $userAgent, $matches)) {
           
$version = $matches[1];
        }
        else {
           
$version = 'unknown';
        }

       
// Running on what platform?
       
if (preg_match('/linux/', $userAgent)) {
           
$platform = 'linux';
        }
        elseif (
preg_match('/macintosh|mac os x/', $userAgent)) {
           
$platform = 'mac';
        }
        elseif (
preg_match('/windows|win32/', $userAgent)) {
           
$platform = 'windows';
        }
        else {
           
$platform = 'unrecognized';
        }

        return array(
           
'name'      => $name,
           
'version'   => $version,
           
'platform'  => $platform,
           
'userAgent' => $userAgent
       
);
    }
}

Usage:
$browser = TkBrowser::detect();
echo
'You browser is '.$browser['name'].' version '.$browser['version'].' running on '.$browser['platform'];
?>

Best regards,

Daniel
assadvirgo at gmail dot com
13-Feb-2009 10:40
This is a very useful function to get user browser. A great utility function for those are fed up of get_browser() issues :)

<?php
function get_user_browser()
{
   
$u_agent = $_SERVER['HTTP_USER_AGENT'];
   
$ub = '';
    if(
preg_match('/MSIE/i',$u_agent))
    {
       
$ub = "ie";
    }
    elseif(
preg_match('/Firefox/i',$u_agent))
    {
       
$ub = "firefox";
    }
    elseif(
preg_match('/Safari/i',$u_agent))
    {
       
$ub = "safari";
    }
    elseif(
preg_match('/Chrome/i',$u_agent))
    {
       
$ub = "chrome";
    }
    elseif(
preg_match('/Flock/i',$u_agent))
    {
       
$ub = "flock";
    }
    elseif(
preg_match('/Opera/i',$u_agent))
    {
       
$ub = "opera";
    }
   
    return
$ub;
}
?>
admin at studio-gepard dot pl
06-Feb-2009 08:57
Daniel Frechette's code shown me "unrecognized" for way too many browsers so I decided to merge small part of his code with tectonikNOSPAM at free dot fr one. I also removed globals (which I never use), and made a function of it. Detects browser and platform. The input can be true - for array - or false - for simple string output. Tested - works on Win, Mac, and browsers specified.

<?php

function checkBrowser($input) {

$browsers = "mozilla msie gecko firefox ";
$browsers.= "konqueror safari netscape navigator ";
$browsers.= "opera mosaic lynx amaya omniweb";

$browsers = split(" ", $browsers);

$userAgent = strToLower( $_SERVER['HTTP_USER_AGENT']);

$l = strlen($userAgent);
for (
$i=0; $i<count($browsers); $i++){
 
$browser = $browsers[$i];
 
$n = stristr($userAgent, $browser);
  if(
strlen($n)>0){
   
$version = "";
   
$navigator = $browser;
   
$j=strpos($userAgent, $navigator)+$n+strlen($navigator)+1;
    for (;
$j<=$l; $j++){
     
$s = substr ($userAgent, $j, 1);
      if(
is_numeric($version.$s) )
     
$version .= $s;
      else
      break;
    }
  }
}

    if (
strpos($userAgent, 'linux')) {
       
$platform = 'linux';
    }
    else if (
strpos($userAgent, 'macintosh') || strpos($userAgent, 'mac platform x')) {
       
$platform = 'mac';
    }
    else if (
strpos($userAgent, 'windows') || strpos($userAgent, 'win32')) {
       
$platform = 'windows';
    }

if (
$input==true) {
        return array(
       
"browser"      => $navigator,
       
"version"      => $version,
       
"platform"     => $platform,
       
"userAgent"    => $userAgent);
}else{
        return
"$navigator $version";
}

}

/* USAGE: */
//array output:
$i = checkBrowser(false);
print_r($i);
//will give:
//Array ( [browser] => firefox [version] => 3.0 [platform] => windows [userAgent] => mozilla/5.0 (windows; u; windows nt 5.1; pl; rv:1.9.0.6) gecko/2009011913 firefox/3.0.6 )

//string output:
echo checkBrowser(true);
//will give: firefox 3.0

?>
Daniel Frechette
13-Nov-2008 07:28
A newer version. Keep in mind that this function does not replace get_browser. It is just a basic version that only looks for certain browsers: IE, Firefox, Safari, Opera and Chrome. All other browsers are "unrecognised".

<?php
function getBrowserInfo() {
   
// Note: An excellent article on browser IDs can be found at
    // http://www.zytrax.com/tech/web/browser_ids.htm

   
$SUPERCLASS_NAMES = "gecko,mozilla,mosaic,webkit";
   
$SUPERCLASS_REGX  = "(?:".str_replace(",", ")|(?:", $SUPERCLASS_NAMES).")";

   
$SUBCLASS_NAMES   = "opera,msie,firefox,chrome,safari";
   
$SUBCLASS_REGX    = "(?:".str_replace(",", ")|(?:", $SUBCLASS_NAMES).")";

   
$browser      = "unrecognized";
   
$majorVersion = "0";
   
$minorVersion = "0";
   
$fullVersion  = "0.0";
   
$platform     = 'unrecognized';

   
$userAgent    = strtolower($_SERVER['HTTP_USER_AGENT']);

   
$found = preg_match("/(?P<browser>".$SUBCLASS_REGX.")(?:\D*)
(?P<majorVersion>\d*)(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches);
    if (!
$found) {
       
$found = preg_match("/(?P<browser>".$SUPERCLASS_REGX.")(?:\D*)
(?P<majorVersion>\d*)(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches);
    }

    if (
$found) {
       
$browser      = $matches["browser"];
       
$majorVersion = $matches["majorVersion"];
       
$minorVersion = $matches["minorVersion"];
       
$fullVersion  = $matches["majorVersion"].$matches["minorVersion"];
        if (
$browser == "safari") {
            if (
preg_match("/version\
/(?P<majorVersion>\d*)(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches)){
               
$majorVersion = $matches["majorVersion"];
               
$minorVersion = $matches["minorVersion"];
               
$fullVersion  = $majorVersion.".".$minorVersion;
            }
        }
    }

    if (
strpos($userAgent, 'linux')) {
       
$platform = 'linux';
    }
    else if (
strpos($userAgent, 'macintosh') || strpos($userAgent, 'mac platform x')) {
       
$platform = 'mac';
    }
    else if (
strpos($userAgent, 'windows') || strpos($userAgent, 'win32')) {
       
$platform = 'windows';
    }

    return array(
       
"browser"      => $browser,
       
"majorVersion" => $majorVersion,
       
"minorVersion" => $minorVersion,
       
"fullVersion"  => $fullVersion,
       
"platform"     => $platform,
       
"userAgent"    => $userAgent);
}
?>
Daniel Frechette
13-Nov-2008 04:41
The Great God Om, I reformatted your script, made a few enhancements and fixed a few errors.

<?php
function getBrowserInfo() {
   
$SUPERCLASS_NAMES  = "gecko,mozilla,mosaic,webkit";
   
$SUPERCLASSES_REGX = "(?:".str_replace(",", ")|(?:", $SUPERCLASS_NAMES).")";

   
$SUBCLASS_NAMES    = "opera,msie,firefox,chrome,safari";
   
$SUBCLASSES_REGX   = "(?:".str_replace(",", ")|(?:", $SUBCLASS_NAMES).")";

   
$browser      = "unsupported";
   
$majorVersion = "0";
   
$minorVersion = "0";
   
$fullVersion  = "0.0";
   
$os           = 'unsupported';

   
$userAgent    = strtolower($_SERVER['HTTP_USER_AGENT']);

   
$found = preg_match("/(?P<browser>".$SUBCLASSES_REGX.")(?:\D*)
(?P<majorVersion>\d*)(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches);
    if (!
$found) {
       
$found = preg_match("/(?P<browser>".$SUPERCLASSES_REGX.")(?:\D*)
(?P<majorVersion>\d*)(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches);
    }
   
    if (
$found) {
       
$browser      = $matches["browser"];
       
$majorVersion = $matches["majorVersion"];
       
$minorVersion = $matches["minorVersion"];
       
$fullVersion  = $matches["majorVersion"].$matches["minorVersion"];
        if (
$browser != "safari") {
            if (
preg_match("/version\/(?P<majorVersion>\d*)
(?P<minorVersion>(?:\.\d*)*)/i"
,
$userAgent, $matches)){
               
$majorVersion = $matches["majorVersion"];
               
$minorVersion = $matches["minorVersion"];
               
$fullVersion  = $majorVersion.".".$minorVersion;
            }
        }
    }

    if (
strpos($userAgent, 'linux')) {
       
$os = 'linux';
    }
    else if (
strpos($userAgent, 'macintosh') || strpos($userAgent, 'mac os x')) {
       
$os = 'mac';
    }
    else if (
strpos($userAgent, 'windows') || strpos($userAgent, 'win32')) {
       
$os = 'windows';
    }

    return array(
       
"browser"      => $browser,
       
"majorVersion" => $majorVersion,
       
"minorVersion" => $minorVersion,
       
"fullVersion"  => $fullVersion,
       
"os"           => $os);
}
?>
addw at phcomp dot co dot uk
19-Aug-2008 05:59
For automatic updates of the browser database you can find a script here:  http://www.phcomp.co.uk/downloads.php#php
Install and run out of cron.
The Great God Om
05-May-2008 04:23
Regexes to extract browser name and version info from a user agent string.  If it doesn't find a browser name from the "subclass" list it tries the "superclass" list.

<?
$subclass = "MSIE,Firefox,Konqueror,Safari,Opera,
        Netscape,Navigator,Lynx,Amaya,Omniweb";
$superclass = "Gecko,Mozilla,Mosaic,Webkit";
$subclassregex = "(?:" . str_replace(",",")|(?:",$subclass) . ")";
$superclassregex = "(?:" . str_replace(",",")|(?:",$subclass) . ")";

$browser_name = "unrecognized";
$browser_majorversion = 0;
$browser_fullversion = "0.0";

$bsuperclassmatch = FALSE;
$bsubclassmatch = preg_match("/(?<browser>" . $subclassregex . ")(?:\D*)(?<majorversion>\d*)
        (?<subversion>(?:\.\d*)*)/i", $_SERVER['HTTP_USER_AGENT'], $matches);
if (!$bsubclassmatch){
    $bsuperclassmatch = preg_match("/(?<browser>" . $superclassregex . ")(?:\D*)(?<majorversion>\d*)
        (?<subversion>(?:\.\d*)*)/i", $_SERVER['HTTP_USER_AGENT'], $matches);
}
if ($bsubclassmatch||$bsuperclassmatch){
    $browser_name = strtolower($matches["browser"]);
    $browser_majorversion = (int)$matches["majorversion"];
    $browser_fullversion = $matches["majorversion"].$matches["subversion"];
    if (!strcasecmp($browser_name, "Safari")){
        $safarimatch = preg_match("/Version\/(?<majorversion>\d*)
        (?<subversion>(?:\.\d*)*)/i", $_SERVER['HTTP_USER_AGENT'], $safarimatches);
        if ($safarimatch){
            $browser_majorversion = (int)$safarimatches["majorversion"];
            $browser_fullversion = $safarimatches["majorversion"].$safarimatches["subversion"];
        }
    }
}
?>
ck+php dot net at animepaper dot net
04-Jan-2008 06:25
latest update for php_browscap.ini
should be download at http://browsers.garykeith.com/stream.asp?PHP_BrowsCapINI

for others version (i.e: xml, csv etc)
http://browsers.garykeith.com/faq.asp
jesdisciple [at] gmail -dawt- com
19-Nov-2007 02:13
Use this to ensure that the costly call in its standard form never needs to be repeated:
<?php
function getBrowser(){
    static
$browser;//No accident can arise from depending on an unset variable.
   
if(!isset($browser)){
       
$browser = get_browser($_SERVER['HTTP_USER_AGENT']);
    }
    return
$browser;
}
?>
Steffen
19-Oct-2007 08:59
Keep in mind that get_browser(); really slows down your application.  It takes about 22 ms to execute on an idle server with Ubuntu Linux, Apache 2, PHP 5.1.3.
digibrisk at gmail dot NOSPAM dot SPAMNO dot com
06-Oct-2007 10:20
If the "browscap" directive isn't set in your server's php.ini, then an error warning is shown. Just in case, you could make a call to ini_get() to check if the browscap directive is set before using browser_get().

<?php
if(ini_get("browscap")) {
   
$browser = get_browse(null, true);
}
?>
mike at mike-griffiths dot co dot uk
23-Jul-2007 07:41
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.
ansar dot ahmed at impelsys dot com
22-Mar-2007 08:01
We are using get_browser() function for useragent Mozilla/4.0 (compatible; MSIE 4.01; Windows NT) the get_browser function is returning as Default Browser and Platform = unknown.

So i added this to my browscap.ini manually:

[Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)]
Parent=IE 4.01
Platform=WinNT
sam
22-Oct-2006 08:09
I thought this function might be useful to those without access to the php.ini file (such as those on a shared hosting system):

function php_get_browser($agent = NULL){
$agent=$agent?$agent:$_SERVER['HTTP_USER_AGENT'];
$yu=array();
$q_s=array("#\.#","#\*#","#\?#");
$q_r=array("\.",".*",".?");
$brows=parse_ini_file("php_browscap.ini",true);
foreach($brows as $k=>$t){
  if(fnmatch($k,$agent)){
  $yu['browser_name_pattern']=$k;
  $pat=preg_replace($q_s,$q_r,$k);
  $yu['browser_name_regex']=strtolower("^$pat$");
    foreach($brows as $g=>$r){
      if($t['Parent']==$g){
        foreach($brows as $a=>$b){
          if($r['Parent']==$a){
            $yu=array_merge($yu,$b,$r,$t);
            foreach($yu as $d=>$z){
              $l=strtolower($d);
              $hu[$l]=$z;
            }
          }
        }
      }
    }
    break;
  }
}
return $hu;
}
define the location of php_browscap.ini wherever you want
always returns an array, same functionality as get_browser(NULL,true)
Hope someone finds it useful!
st DOT jonathan AT gmail DOT com
02-Oct-2006 05:36
Here is a class I've created that supports an external browscap.ini file (configuration independent) and works faster than get_browser on multiple queries.

http://garetjax.info/projects/browscap/
adspeed.com
02-Sep-2005 03:06
Here is what we do to fix the parsing error messages for php_browscap.ini downloaded from Gary's website.

<?php
// fix the browsecap.ini for php
$v= file_get_contents('php_browscap.ini');
$v= preg_replace("/\r/","",$v);
$v= preg_replace('/="(.*)"/i','=\\1',$v);
$v= preg_replace("/platform=(.*)/i","platform=\"\\1\"",$v);
$v= preg_replace("/parent=(.*)/i","parent=\"\\1\"",$v);
$v= preg_replace("/minorver=(.*)/i","minorver=\"\\1\"",$v);
$v= preg_replace("/majorver=(.*)/i","majorver=\"\\1\"",$v);
$v= preg_replace("/version=(.*)/i","version=\"\\1\"",$v);
$v= preg_replace("/browser=(.*)/i","browser=\"\\1\"",$v);
$v= str_replace("[*]","*",$v);
file_put_contents('browscap.ini',$v);
?>
pal at degerstrom dot com
26-Apr-2005 11:13
This might be useful for some until the Gary Keith updates his library. I added this to my browscap.ini to detect the latest Safari update for Panther, and the new Safari in Tiger:

;;; Added manually 05.04.19 for Safari 1.3
[Mozilla/5.0 (Macintosh; U; PPC Mac OS X; *) AppleWebKit/* (*) Safari/31?]
parent=Safari
version=1.3
majorver=1
minorver=3

;;; Added manually 05.04.26 for Safari 2.0 (Shipped with Tiger)
[Mozilla/5.0 (Macintosh; U; PPC Mac OS X; *) AppleWebKit/* (*) Safari/41?]
parent=Safari
version=2.0
majorver=2
minorver=0

Note: Full $_SERVER['HTTP_USER_AGENT'] for Safari 2 (Tiger) is
     Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412 (KHTML, like Gecko) Safari/412

(Disclaimer: I do not know if the entries above conform to whatever syntax standard Gary uses in his file, but it works fine for me).

Pål Degerstrøm
tectonikNOSPAM at free dot fr
07-Apr-2005 07:17
Another (short) sequential php script to determine browsers family and version.
<?
//        _______
// ----- | CONF. |
//        ¯¯¯¯¯¯¯
// add new browsers in lower case here, separated
// by spaces -  order is important: from left to
// right browser family becomes more precise
$browsers = "mozilla msie gecko firefox ";
$browsers.= "konqueror safari netscape navigator ";
$browsers.= "opera mosaic lynx amaya omniweb";

//        _______
// ----- |PROCESS|
//        ¯¯¯¯¯¯¯
$browsers = split(" ", $browsers);

$nua = strToLower( $_SERVER['HTTP_USER_AGENT']);

$l = strlen($nua);
for ($i=0; $i<count($browsers); $i++){
  $browser = $browsers[$i];
  $n = stristr($nua, $browser);
  if(strlen($n)>0){
    $GLOBALS["ver"] = "";
    $GLOBALS["nav"] = $browser;
    $j=strpos($nua, $GLOBALS["nav"])+$n+strlen($GLOBALS["nav"])+1;
    for (; $j<=$l; $j++){
      $s = substr ($nua, $j, 1);
      if(is_numeric($GLOBALS["ver"].$s) )
      $GLOBALS["ver"] .= $s;
      else
      break;
    }
  }
}

//        _______
// ----- |  USE  |
//        ¯¯¯¯¯¯¯
echo("<pre>Your browser is: ");
echo($GLOBALS["nav"] . " " . $GLOBALS["ver"] . "</pre>");
?>

source: http://tectonik.free.fr/technos/php/
another%20PHP%20browser%20sniffer.php
hh
28-Jun-2004 05:19
Another PHP browser detection script that might be of use to you is here:
http://tech.ratmachines.com/downloads/php_browser_detection.php
This script uses a fairly different logic than get_browser, and doesn't worry about things like table/frame ability. This script was being used by mozdev to id Mozilla versions, since it specializes in that kind of specialized id. It also has unix/linux version os iding.
max at phpexpert dot de
26-Mar-2004 01:14
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.
bishop
05-Aug-2003 04:46
PHP is sensitive to characters outside the range [ A-Za-z0-9_] as values in .ini files.  For example

browser=Opera (Bork Version)

causes PHP to complain, as it doesn't like the parentheses.

If you place quotation marks around the values for all keys in the browscap.ini file, you'll save yourself parsing problems.  Do this in eg vi with %s/=\(.*\)/="\1"/g

You could of course use PHP itself to fixup the file.  Exercise left to the reader.
verx at implix dot com
09-Dec-2002 08:57
Please keep in mind that you should somehow (for example in session) cache the required results of get_browser() because it really slows thinks down.

We have experienced that without querying for browser data our scripts would run 120-130% faster. the explanation is that over 200kb long file (browscap.ini) has to be loaded and parsed everytime someone access any page (we need browser results on all pages).

So keep results in session and expect a performance boost.
les at hazlewood dot com
03-Sep-2001 11:57
phpSniff (noted in a few places above) is absolutely fantastic.  I just installed it, and it is a godsend!  It now handles all of my session information needed to go in my database.  Thanks for you folks who posted that great Sourceforge resource!  http://phpsniff.sourceforge.net/
philip at cornado dot com
26-Aug-2001 01:05
nick at category4 dot com
12-Jun-2001 09:21
Here's a quick way to test for a Netscape browser.  IE and Konqueror and several others call themselves "Mozilla", but they always qualify it with the word "compatible."

$isns = stristr($HTTP_USER_AGENT, "Mozilla") && (!(stristr($HTTP_USER_AGENT, "compatible")));
triad at df dot lth dot se
30-Jul-2000 09:17
The only way browscap examines the target browser is through the HTTP_USER_AGENT so there is no way you can determine installed plug-ins. The only way to do that is through client-side JavaScripts.

__halt_compiler> <exit
Last updated: Fri, 06 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites