|
|
 |
get_browser (PHP 3, PHP 4, PHP 5) get_browser --
Indica las capacidades del navegador del usuario
Descripciónmixed get_browser ( [string agente_usuario [, bool matriz_retorno]] )
get_browser() intenta determinar las
capacidades del navegador del usuario. Para ello consulta el
archivo de información del navegador,
browscap.ini.
Por omisión, se utiliza el valor de la cabecera HTTP
User-Agent; sin embargo, puede alterar este comportamiento (es
decir, consultar la información de otro navegador) pasando
el parámetro opcional
agente_usuario a
get_browser(). Es posible ignorar el
parámetro agente_usuario con el
valor NULL.
La información se devuelve en un object, el
cual contendrá varios elementos de datos que representan,
por ejemplo, los números de versión mayor y menor
del navegador y la cadena ID; valores TRUE/FALSE para
caracterÃsticas como los frames, JavaScript, y cookies; y
asà sucesivamente.
A partir de PHP 4.3.2, si el parámetro opcional
matriz_retorno es TRUE, esta
función devuelve un valor array en lugar de
object.
Ejemplo 1. Listar toda la información sobre el navegador del
usuario |
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$navegador = get_browser(null, true);
print_r($navegador);
?>
|
El resultado del ejemplo seria algo
similar a: 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] =>
) |
|
El valor cookies simplemente quiere decir que
el navegador mismo tiene la capacidad de aceptar cookies y no
quiere decir que el usuario haya habilitado el navegador para que
acepte cookies o no. La única manera de probar si las
cookies son aceptadas es definir una con
setcookie(), recargar, y chequear el valor.
Nota:
Para que ésto funcione, su opción de
configuración browscap en php.ini debe apuntar
a la ubicación correcta del archivo
browscap.ini en su sistema.
browscap.ini no hace parte de la
distribución de PHP, pero puede encontrar un archivo browscap.ini
actualizado aquÃ.
Aunque browscap.ini contiene
información sobre varios navegadores, depende de
actualizaciones de usuario para mantener la base de datos al
dÃa. El formato del archivo es bastante auto-explicativo.
znupi69 at at at gmail dot dot dot com
28-Aug-2006 05:41
I hope some will find this useful ... It doesn't use any preg_replace(); so I think that makes it faster (not shure though). Also I haven't tested it with all browsers (just firefox and ie), but my guess is it will detect any ...
<?php
function detectBrowser() {
$browsers = array("msie", "firefox"); $names = array ("msie" => "Microsoft Internet Explorer", "firefox" => "Mozilla Firefox"); $nav = "Unknown";
$sig = strToLower ($_SERVER['HTTP_USER_AGENT']);
foreach ($browsers as $b) {
if ( $pos = strpos ($sig, $b) ) {
$nav = $names[$b];
break;
}
}
if ($nav == "Unknown") return array ("app.Name" => $nav, "app.Ver" => "?", "app.Sig" => $sig);
$ver = "";
for ( ; $pos <= strlen ($sig); $pos ++) {
if ( (is_numeric($sig[$pos])) || ($sig[$pos]==".") ) {
$ver .= $sig[$pos];
}
else if ($ver) break;
}
return array("app.Name" => $nav, "app.Ver" => $ver, "app.Sig" => $sig);
}
$nav = detectBrowser();
echo "Your browser is: " . $nav['app.Name'] . " " . $nav['app.Ver'] . "<br />Your signature was: " . $nav['app.Sig'];
?>
Hope I helped :)
steven Cambridge UK
16-Mar-2006 02:40
the function _get_browser() by fotos at uop dot gr has a few errors..well at least i had to change it to get it to work for me.
so...
$info[browser] = $parent;
$info[version] = $version;
becomes
$info['browser'] = $parent;
$info['version'] = $version;
and i use...
$browser = _get_browser();
if ($browser['browser'] == "MSIE").....
martin at boreal dot org dot uk
16-Dec-2005 02:03
Small comment regarding fotos at uop dot gr
the line:
$version = substr($_SERVER['HTTP_USER_AGENT'], $f, 5);
needs to be:
$version = substr($_SERVER['HTTP_USER_AGENT'], $f, 6);
for Firefox incremental updates to show up.
fotos at uop dot gr
21-Oct-2005 07:35
Regarding the code by steve (in Feb) and somewhat corrected by matt there is another ugly bug laying around:
Opera when set to report as IE returns the following header:
"Mozilla/4.0 (compatible; MSIE 6.0; Mac_PowerPC Mac OS X; en) Opera 8.5"
Well in the code given the last matching $browser in the array wins, and in this case the code reports "Mozilla" which is totally unexpected!
But Safari gives:
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/412.7 (KHTML, like Gecko) Safari/412.5"
The solution I can think of is to first search for more specific browsers and then for more generic (also seems more reasonable). If something matches then we are done. But probably this is not a catch all solution, but a good starting point.
So the code becomes:
<?php
function _get_browser()
{
$browser = array ( "OPERA",
"MSIE", "NETSCAPE",
"FIREFOX",
"SAFARI",
"KONQUEROR",
"MOZILLA" );
$info[browser] = "OTHER";
foreach ($browser as $parent)
{
if ( ($s = strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent)) !== FALSE )
{
$f = $s + strlen($parent);
$version = substr($_SERVER['HTTP_USER_AGENT'], $f, 5);
$version = preg_replace('/[^0-9,.]/','',$version);
$info[browser] = $parent;
$info[version] = $version;
break; }
}
return $info;
}
?>
matt at axia dot org dot uk
13-Oct-2005 03:36
This is a fix for a bug in the code left by steve (in Feb). Basically, if the search for the browser type was at the beginning of the 'HTTP_USER_AGENT' (ie. the first character) then strpos returns 0 causing, the code to drop out incorrectly. I also trimmed the code to make it more efficient.
function _get_browser()
{
$browser = array (
"MSIE", // parent
"OPERA",
"MOZILLA", // parent
"NETSCAPE",
"FIREFOX",
"SAFARI"
);
$info[browser] = "OTHER";
foreach ($browser as $parent)
{
if ( ($s = strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent)) !== FALSE )
{
$f = $s + strlen($parent);
$version = substr($_SERVER['HTTP_USER_AGENT'], $f, 5);
$version = preg_replace('/[^0-9,.]/','',$version);
$info[browser] = $parent;
$info[version] = $version;
}
}
return $info;
}
adspeed.com
02-Sep-2005 10:06
Here is what we do to fix the parsing error messages for php_browscap.ini downloaded from Gary's website.
<?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 06: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 02:17
Another (short) sequential php script to determine browsers family and version.
<?
$browsers = "mozilla msie gecko firefox ";
$browsers.= "konqueror safari netscape navigator ";
$browsers.= "opera mosaic lynx amaya omniweb";
$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;
}
}
}
echo("<pre>Your browser is: ");
echo($GLOBALS["nav"] . " " . $GLOBALS["ver"] . "</pre>");
?>
source: http://tectonik.free.fr/technos/php/
another%20PHP%20browser%20sniffer.php
jasperbg at gmail dot com
02-Apr-2005 08:23
To :: TomkOx ::
It's actually better to use strpos(). You need to use === or !== rather than == or != to check the return value though, otherwise you'll get 0 which equates to false when the string is found at position 0.
For example:
<?php
if(strpos($haystack, $needle) !== false) {
} else {
}
?>
That'll work for any position, even 0.
:: TomkOx ::
30-Mar-2005 10:12
It is not good to use function: strpos() in detecting browser or OS by HTTP_USER_AGENT. Better is to use function strstr() becouse some strings returned by HTTP_USER_AGENT have 'needed information' at 1st (0) position of the string. Function strpos() 'will not find' for eg. signature of Opera on OSX. I think it's better to use like this (example):
<?
Class SomeDetectoriumClass {
function aboutNetGuest() {
$curos=strtolower($_SERVER['HTTP_USER_AGENT']);
$uip=$_SERVER['REMOTE_ADDR'];
$uht=gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (strstr($curos,"mac")) {
$uos="MacOS";
} else if (strstr($curos,"linux")) {
$uos="Linux";
} else if (strstr($curos,"win")) {
$uos="Windows";
} else if (strstr($curos,"bsd")) {
$uos="BSD";
} else if (strstr($curos,"qnx")) {
$uos="QNX";
} else if (strstr($curos,"sun")) {
$uos="SunOS";
} else if (strstr($curos,"solaris")) {
$uos="Solaris";
} else if (strstr($curos,"irix")) {
$uos="IRIX";
} else if (strstr($curos,"aix")) {
$uos="AIX";
} else if (strstr($curos,"unix")) {
$uos="Unix";
} else if (strstr($curos,"amiga")) {
$uos="Amiga";
} else if (strstr($curos,"os/2")) {
$uos="OS/2";
} else if (strstr($curos,"beos")) {
$uos="BeOS";
} else { $uos="[?]EgzoticalOS";
}
if (strstr($curos,"gecko")) {
if (strstr($curos,"safari")) {
$bos="Safari";
} else if (strstr($curos,"camino")) {
$bos="Camino";
} else if (strstr($curos,"firefox")) {
$bos="Firefox";
} else if (strstr($curos,"netscape")) {
$bos="Netscape";
} else { $bos="Mozilla";
}
} else if (strstr($curos,"opera")) {
$bos="Opera";
} else if (strstr($curos,"msie")) {
$bos="Internet Exploder";
} else if (strstr($curos,"voyager")) {
$bos="Voyager";
} else if (strstr($curos,"lynx")) {
$bos="Lynx";
} else { $bos="[?]EgzoticalBrowser";
}
return array ($uos,$bos,$uip,$uht);
} ?>
Regards from Poland, TomkOx. ;)
steve
11-Feb-2005 04:17
displays browser and version # in an array.
<?php
$browser = array (
"MSIE", "OPERA",
"MOZILLA", "NETSCAPE",
"FIREFOX",
"SAFARI"
);
$info[browser] = "OTHER";
foreach ($browser as $parent) {
$s = strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent);
$f = $s + strlen($parent);
$version = substr($_SERVER['HTTP_USER_AGENT'], $f, 5);
$version = preg_replace('/[^0-9,.]/','',$version);
if (strpos(strtoupper($_SERVER['HTTP_USER_AGENT']), $parent)) {
$info[browser] = $parent;
$info[version] = $version;
}
}
print_r($info);
?>
Melchior (webmaster at ffx-ultima dot com)
24-Oct-2004 08:33
My contribution for detected the browsers
<?php
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') )
{
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Netscape') )
{
$browser = 'Netscape (Gecko/Netscape)';
}
else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') )
{
$browser = 'Mozilla Firefox (Gecko/Firefox)';
}
else
{
$browser = 'Mozilla (Gecko/Mozilla)';
}
}
else if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') )
{
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') )
{
$browser = 'Opera (MSIE/Opera/Compatible)';
}
else
{
$browser = 'Internet Explorer (MSIE/Compatible)';
}
}
else
{
$browser = 'Others browsers';
}
echo $browser;
?>
Melchior ;)
hh
28-Jun-2004 12: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 07: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 11: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 02: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 06: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/
nick at category4 dot com
12-Jun-2001 04: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 04: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.
andysmith at post dot com
06-May-2000 02:04
the example is great if you just want to spit out all that stuff, but i highly doubt anybody really wants to do that. To use the get_browser object in a conditional statement, do something like this:
$ua = get_browser ();
if ( ( $ua->browser == "Netscape" ) && ( $ua->version < 5 ) ) {
// code to fix the page for netscape :)
}
| |
| | Citas célebres | El verso, hijo de la emoción, ha de ser fino y profundo, como una nota de arpa. No se ha de decir lo raro, sino el instante raro de la emoción noble o gloriosa. José Martí Político y escritor cubano (1853-1895) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Médicos | | Confusión telefónica | El hospital recibe una llamada telefónica:
- ¡Mi mujer va a dar a luz!
- ¿Es su primer hijo?
- No. ¡Soy su marido! | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|