PHP
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, 26 Dec 2008

view this page in

get_browser

(PHP 4, PHP 5)

get_browserIndique de quoi est capable le navigateur client

Description

mixed get_browser ([ string $user_agent [, bool $return_array ]] )

Essaie de déterminer les capacités du navigateur client. Cela se fait en lisant les informations dans le fichier browscap.ini.

Liste de paramètres

user_agent

L'entête user agent à analyser. Par défaut, la valeur de l'en-tête User-Agent est utilisé ; cependant, vous pouvez l'altérer (i.e. cherche d'autres informations sur le navigateur) en passant ce paramètre.

Vous pouvez annuler ce paramètre en y passant la valeur NULL.

return_array

Si définit à TRUE, cette fonction retournera un tableau au lieu d'un object.

Valeurs de retour

Les informations sont retournées sous forme d'un objet, dont les différents membres contiendront des informations, telles que les versions majeures et mineures et des chaînes d'identification ; des booléens pour des caractéristiques telles que frames, JavaScript, et cookies ; et ainsi de suite.

La valeur cookies indique simplement que le navigateur est capable d'accepter les cookies, et n'indique pas si l'utilisateur les a activé sur son navigateur. Le seul moyen de tester l'activation des cookies est d'en poser un avec la fonction setcookie(), de recharger la page et de vérifier que le cookie existe toujours.

Historique

Version Description
4.3.2 Le paramètre optionnel return_array a été ajouté.

Exemples

Exemple #1 Exemple avec get_browser() : liste des capacités du navigateur du client

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser get_browser(nulltrue);
print_r($browser);
?>

L'exemple ci-dessus va afficher quelque chose de similaire à :

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
    [css] => 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: Afin de pouvoir fonctionner, la directive de configuration browscap dans le fichier php.ini doit pointer vers le fichier browscap.ini de votre système.
browscap.ini n'est pas distribué avec PHP, mais vous pouvez le télécharger sur » php_browscap.ini.
Bien que browscap.ini contienne des informations sur de très nombreux navigateur, il incombe à l'utilisateur de conserver sa base de données à jour. Le format du fichier est très simple à comprendre.



__halt_compiler> <exit
Last updated: Fri, 26 Dec 2008
 
add a note add a note User Contributed Notes
get_browser
Daniel Frechette
13-Nov-2008 10: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 07: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 09: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 08: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 09: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 05: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 12: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 02: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 11: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 11: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
23-Oct-2006 12: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 09: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 07: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 03: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 11: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 09: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 04: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 08: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 11: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
04-Sep-2001 03: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 05:05
nick at category4 dot com
13-Jun-2001 01: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
31-Jul-2000 01: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, 26 Dec 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites