problema dell'user agent di un browser

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
Uso questo codice:
$browser = $_SERVER["HTTP_USER_AGENT"];

mi dite come si fa a mettere solo il nome del browser e levare tutto questo codice:
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36

grazie mille.
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
ho risolto con questo codice vedendo i link che mi hai postato..

e funziona .. ho visto che non serve installare niente..perché usa le regex giusto?

PHP:
<?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);
?>

ti ringrazio molto.
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
ok problema uno...


ho provato con ie e chrome.. chrome lo vede..

ma ie no e mi segnala:
Notice: Undefined variable: ub in

come mai ad queste righe:
$known = array('Version', $ub, 'other');

if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){

come mai?

grazie mille.
 

MarcoGrazia

Utente Attivo
15 Dic 2009
852
20
28
62
Udine
www.stilisticamente.com
Ci sono un po' troppi come mai :D
Come mai non c'è un else?
Voglio dire ed è questo il tuo problema, se non viene rilevato explorer cosa diventa $ub ?
cioè bname è dichiarato unknow ( sconosciuto ) ma ub non è proprio preso in considerazione! Metti all'inizio anche $ub = 'unknow' e io aggiungerei anche $platform = 'unknow' e vedio che l'errore sparisce, ovvio non risolve il perché IE non lo legge, magari stampati echo $_SERVER[HTTP_USER_AGENT]; tanto per vedere cosa scrive.
Tieni presente che uno script del genere da un sacco di falssi positivi perché la stringa browser è molto aleatoria, uno la può modificare quando vuole con ciò che vuole.
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
ho fatto una prova con un codice più piccolo e il problema sta:
PHP:
<?php
function getBrowser($str)
{
$browser = $_SERVER['HTTP_USER_AGENT'];
$chrome = '/Chrome/';
$firefox = '/Firefox/';
$ie = '/MSIE/';
if (preg_match($chrome, $browser))
    $str = "Chrome/Opera";
if (preg_match($firefox, $browser))
    $str =  "Firefox";
if (preg_match($ie, $browser))
    $str = "Ie"; 
	return $str;
}
 echo ''.getBrowser($_SERVER['HTTP_USER_AGENT']).'';
?>

che firefox, chrome .. rileva il nome esatto.

ma internet explorer invece di scrivere IE,
mi scrive:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko

avendo l'11 con windows 7. ?

idea?

grazie mille.
 

luigi777

Utente Attivo
14 Feb 2008
1.086
1
38
42
Massa, Italy
ho risolto con questo anche se ho dovuto togliere delle parti per farlo funzionare al mio codice:

http://drupalcontrib.org/api/drupal/contributions!themekey_properties!browser_detection.php/function/BrowserDetection%3A%3AgetBrowser/6

il codice:
PHP:
<?php 
function getBrowser($useragent) {
  // check for most popular browsers first
  // unfortunately, that's IE. We also ignore Opera and Netscape 8
  // because they sometimes send msie agent
  if (strpos($useragent, 'MSIE') !== FALSE && strpos($useragent, 'Opera') === FALSE && strpos($useragent, 'Netscape') === FALSE) {
    //deal with Blazer
    if (preg_match("/Blazer\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Blazer ' . $matches[1];
    }
    //deal with IE
    if (preg_match("/MSIE ([0-9]{1,2}\.[0-9]{1,2})/", $useragent, $matches)) {
      return 'Internet Explorer ' . $matches[1];
    }
  }
  elseif (strpos($useragent, 'IEMobile') !== FALSE) {
    if (preg_match("/IEMobile\/([0-9]{1,2}\.[0-9]{1,2})/", $useragent, $matches)) {
      return 'Internet Explorer Mobile ' . $matches[1];
    }
  }
  elseif (strpos($useragent, 'Gecko')) {
    //deal with Gecko based

    //if firefox
    if (preg_match("/Firefox\/([0-9]{1,2}\.[0-9]{1,2}(\.[0-9]{1,2})?)/", $useragent, $matches)) {
      return 'Mozilla Firefox ' . $matches[1];
    }

    //if Netscape (based on gecko)
    if (preg_match("/Netscape\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Netscape ' . $matches[1];
    }

    //check chrome before safari because chrome agent contains both
    if (preg_match("/Chrome\/([^\s]+)/", $useragent, $matches)) {
      return 'Google Chrome ' . $matches[1];
    }

    //if Safari (based on gecko)
    if (preg_match("/Safari\/([0-9]{2,3}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Safari ' . $matches[1];
    }

    //if Galeon (based on gecko)
    if (preg_match("/Galeon\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Galeon ' . $matches[1];
    }

    //if Konqueror (based on gecko)
    if (preg_match("/Konqueror\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Konqueror ' . $matches[1];
    }

    // if Fennec (based on gecko)
    if (preg_match("/Fennec\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Fennec' . $matches[1];
    }

    // if Maemo (based on gecko)
    if (preg_match("/Maemo\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Maemo' . $matches[1];
    }

    //no specific Gecko found
    //return generic Gecko
    return 'Gecko based';
  }
  elseif (strpos($useragent, 'Opera') !== FALSE) {
    //deal with Opera
    if (preg_match("/Opera[\/ ]([0-9]{1}\.[0-9]{1}([0-9])?)/", $useragent, $matches)) {
      return 'Opera ' . $matches[1];
    }
  }
  elseif (strpos($useragent, 'Lynx') !== FALSE) {
    //deal with Lynx
    if (preg_match("/Lynx\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Lynx ' . $matches[1];
    }
  }
  elseif (strpos($useragent, 'Netscape') !== FALSE) {
    //NN8 with IE string
    if (preg_match("/Netscape\/([0-9]{1}\.[0-9]{1}(\.[0-9])?)/", $useragent, $matches)) {
      return 'Netscape ' . $matches[1];
    }
  }
  else {
    //unrecognized, this should be less than 1% of browsers (not counting bots like google etc)!
    return 'unknown';
  }
}
?>
<?php echo getBrowser($_SERVER["HTTP_USER_AGENT"]); ?>


e giusto?

perché questo penso di si . essendo di drupal.. penso che sia giusto?

buona serata.
 

MarcoGrazia

Utente Attivo
15 Dic 2009
852
20
28
62
Udine
www.stilisticamente.com
E' come il tuo solo un po' più preciso sul riconoscimento delle stringhe e riguardo a quegli zozzoni della Microsoft.
Non userei mai una funzione del genere se non per dare indicazioni di massima; come hai notato tu stesso, Microsoft ha modificata la stringa di identificazione al punto che il vecchio script non lo rilevava più, quindi è sempre un'indicazione aleatoria.
 
Discussioni simili
Autore Titolo Forum Risposte Data
P problema con il countdown per la fine dell'anno e per natale Javascript 13
C Problema con visualizzazione dell'immagina da tabella database PHP 5
I Sto progettando nuovi siti utilizzando bootstrap e devo dire funziona bene, l'unico problema e la maschera -moz- HTML e CSS 0
K Problema form update PHP 2
O problema con dvr dahua xvr5116 IP Cam e Videosorveglianza 0
S Problema nel ciclare un json Javascript 0
G Problema con Xampp Web Server 1
andrea barletta Problema con miniature comandi Photoshop 0
I problema con alice Posta Elettronica 0
K Problema Inner join PHP 1
F firefox problema http Linux e Software 0
N Problema con position absolute e overflow HTML e CSS 4
E Problema jquery Success jQuery 2
L Problema con inner join PHP 11
K [php] Problema con inner join PHP 4
E problema selezione sfumata Photoshop 2
K [PHP] Problema con variabili concatenate. PHP 1
A Problema filtro fluidifica Photoshop Photoshop 1
H Problema Bordi Scontorno Photoshop 1
O problema con query PHP 4
R Problema installazione Realtek WiFi USB rtl8821 Reti LAN e Wireless 0
I problema con 2 account Posta Elettronica 1
L problema collegamento file css con html HTML e CSS 1
Y Problema percorso file in rete PHP 1
N Problema SEO "L'URL non si trova su Google" SEO e Posizionamento 4
E Problema accesso a file con app sviluppata con MIT APP INVENTOR 2 Sviluppo app per Android 0
P Problema acquisizione clienti Webdesign e Grafica 1
F NetBeans problema creazione progetto Java Windows e Software 0
M Problema con Try Catch PHP 0
C problema seo + cerco esperto SEO e Posizionamento 11
Sergio Unia Problema con gli eventi del mouse su una data table: Javascript 2
T PROBLEMA CON SESSIONI PHP 3
A Problema, non so, di scale() o transform, oppure altro? HTML e CSS 0
T ALTRO PROBLEMA CON ARRAY PHP PHP 1
R problema con else PHP 0
T PROBLEMA CON ARRAY PHP 8
L problema con query select PHP 2
R Problema query con ricerca id numerico PHP 2
F Problema con risposta PHP 0
S problema con recupero dati tabella mysql PHP 2
Z Problema con il mio tp-l i nk Reti LAN e Wireless 1
I PROBLEMA: Sostituzione sito XAMPP E-Commerce 0
T problema data 30/11/-1 PHP 0
L Problema RAM con Tomcat 8 Apache 0
napuleone problema con sort e asort PHP 4
Y Problema incolonnamento tabella PHP 7
S problema salvataggio immagini Photoshop 0
Z Problema con INT MySQL PHP 1
Z Problema database MySQL con XAMPP PHP 0
M Problema con controllo form in real time jQuery 6

Discussioni simili