2010-02-13 13 views
27

Cercare di rilevare il browser di un utente solo con PHP, è $ _SERVER ['HTTP_USER_AGENT'] un modo affidabile? Dovrei invece optare per la funzione get_browser? quale trovi porti risultati più precisi?rilevamento affidabile del browser utente con php

Se questo metodo è pragmatico, si è mal consigliato di utilizzarlo per l'uscita link CSS pertinenti, per esempio:

if(stripos($_SERVER['HTTP_USER_AGENT'],"mozilla")!==false) 
    echo '<link type="text/css" href="mozilla.css" />'; 

ho notato this question, però ho voluto chiarire se questo è un bene per i CSS-oriented rilevamento.

UPDATE: qualcosa di veramente sospetto: Ho provato echo $_SERVER['HTTP_USER_AGENT']; su IE 7 e questo è quello che in uscita:

Mozilla/4.0 (compatible; .NET; MSIE 7.0; Windows NT 6.0 ; SLCC1 CLR 2.0.50727; media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30618)

Safari ha dato qualcosa di strano con "Mozilla" in esso troppo. Cosa dà?

+0

Il bit "Mozilla/4.0" è lì per motivi legacy ... anche in IE8. – scunliffe

+0

IE si identifica per un certo periodo di tempo come Mozilla 4.0. Ho letto che lo hanno fatto per ragioni di compatibilità, ma non sono in grado di trovare la fonte al momento.Se dovessi indovinare, direi che questo è un detrito dal tempo di NetScape/IE. – Bobby

+0

* User-Agent * non è affidabile. Ma è l'unico modo per indovinare. – Gumbo

risposta

15

L'utilizzo di un metodo esistente (ad esempio get_browser) è probabilmente meglio che scrivere qualcosa da soli, poiché ha (meglio) supporto e verrà aggiornato con le versioni più recenti. Potrebbero esserci anche librerie utilizzabili là fuori per ottenere l'id del browser in modo affidabile.

Decodificare il $_SERVER['HTTP_USER_AGENT'] è difficile, dal momento che molti browser hanno dati abbastanza simili e tendono a (errare) ad usarlo per i propri benefici. Ma se vuoi davvero decodificarli, puoi usare le informazioni su this page per tutti gli ID degli agenti disponibili. Questa pagina mostra anche che l'output di esempio appartiene effettivamente a IE 7. Ulteriori informazioni sui campi nell'ID agente stesso sono reperibili su this page, ma come dicevo già i browser tendono ad usarlo per i propri vantaggi e potrebbe essere in un (leggermente) altro formato.

0

Penso che fare affidamento sull'utenteAgent sia un po 'debole che può (ed è) spesso falsificato.

Se si desidera pubblicare CSS solo per IE, utilizzare un commento condizionale.

<link type="text/css" rel="stylesheet" href="styles.css"/><!--for all--> 
<!--[if IE]> 
    <link type="text/css" rel="stylesheet" href="ie_styles.css"/> 
<![endif]--> 

o se volete semplicemente uno per IE6:

<!--[if IE 6]> 
    <link type="text/css" rel="stylesheet" href="ie6_styles.css"/> 
<![endif]--> 

Fin dalla sua un commento Registrati sua ignorato dai browser ... tranne IE che carica, se il caso di prova corrisponde al browser corrente.

+0

Se è falso, a chi importa? Non è che tu stia affidando la sicurezza su di esso, si tratta semplicemente di visualizzare qualcosa all'utente ... –

2

se stripos ($ _ SERVER [ 'HTTP_USER_AGENT'], "mozilla")! == false)

Questo non è un test utile, quasi tutti i browser si identifica come Mozilla.

è $ _SERVER ['HTTP_USER_AGENT'] un modo affidabile?

No.

Dovrei invece optare per la funzione get_browser?

No.

browser-sniffing sul lato server è un gioco perdente. A parte tutti i problemi di cercare di analizzare la stringa UA, i browser che giacciono, i browser oscuri e la possibilità che l'intestazione non sia affatto lì, se si restituiscono contenuti di pagina diversi per un altro browser, è necessario impostare l'intestazione Vary per includere User-Agent, altrimenti i proxy di cache potrebbero restituire la versione errata della pagina al browser sbagliato.

Ma se si aggiunge Vary: User-Agent codice di cache rotto di IE viene confuso e ricarica la pagina ogni volta. Quindi non puoi vincere.

Se è necessario sniffare il browser, il posto per farlo è sul lato client, utilizzando JavaScript e, in particolare nel caso di IE, i commenti condizionali. È fortunato che si tratti di IE che supporta i commenti condizionali, dal momento che è l'unico browser per il quale si ha spesso bisogno di soluzioni alternative. (Vedi la risposta di scunliffe per la strategia più comune.)

6
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 
     ); 
    } 
} 


$browser = Browser::detect(); 
+4

Dice chrome è safari ... –

+0

perché stai creando una classe con un solo metodo? perché non usare invece una funzione normale? –

+0

Questa è la tua scelta fai ciò che vuoi. Sto dando un esempio su come rilevare il browser. Ho preso da uno dei miei progetti di lavoro. Anche l'uso di oggetti è più preferibile per tutti gli sviluppatori. – user1524615

53

Verificare questo codice, ho trovato questo è utile. Non controllare Mozilla perché la maggior parte l'uso del browser questo come stringa user agent

if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) 
    echo 'Internet explorer'; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== FALSE) //For Supporting IE 11 
    echo 'Internet explorer'; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== FALSE) 
    echo 'Mozilla Firefox'; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== FALSE) 
    echo 'Google Chrome'; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== FALSE) 
    echo "Opera Mini"; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== FALSE) 
    echo "Opera"; 
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== FALSE) 
    echo "Safari"; 
else 
    echo 'Something else'; 
+1

Impressionante +1 questo! –

+4

Non funziona per IE 11 (dai un'occhiata qui: http://www.nczonline.net/blog/2013/07/02/internet-explorer-11-dont-call-me-ie/) –

+2

modificato @rap -2-h –

1

vecchio post, viene ancora in Google. get_browser() è la soluzione migliore ma la modifica di php.ini potrebbe essere impossibile. Secondo this post non è possibile ini_set la proprietà browscap. Quindi cosa rimane? phpbrowscap sembra portare a termine il lavoro. La documentazione non sono grandi, quindi se non si vuole che l'aggiornamento automatico (il valore predefinito è acceso), allora è necessario impostare

$bc->updateMethod = phpbrowscap\Browscap::UPDATE_LOCAL; 
$bc->localFile = __DIR__ . "/php_browscap.ini"; 
0
Check This Code :  
    <?php  

class OS_BR{  
private $agent = ""; 
private $info = array(); 

function __construct(){ 
    $this->agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL; 
    $this->getBrowser(); 
    $this->getOS(); 
}  
function getBrowser(){  
    $browser = array("Navigator"   => "/Navigator(.*)/i", 
        "Firefox"    => "/Firefox(.*)/i", 
        "Internet Explorer" => "/MSIE(.*)/i", 
        "Google Chrome"  => "/chrome(.*)/i", 
        "MAXTHON"    => "/MAXTHON(.*)/i", 
        "Opera"    => "/Opera(.*)/i", 
        ); 
    foreach($browser as $key => $value){ 
     if(preg_match($value, $this->agent)){ 
      $this->info = array_merge($this->info,array("Browser" => $key)); 
      $this->info = array_merge($this->info,array(
       "Version" => $this->getVersion($key, $value, $this->agent))); 
      break; 
     }else{ 
      $this->info = array_merge($this->info,array("Browser" => "UnKnown")); 
      $this->info = array_merge($this->info,array("Version" => "UnKnown")); 
     } 
    } 
    return $this->info['Browser']; 
} 
function getOS(){ 
    $OS = array("Windows" => "/Windows/i", 
       "Linux"  => "/Linux/i", 
       "Unix"  => "/Unix/i", 
       "Mac"  => "/Mac/i" 
       ); 

    foreach($OS as $key => $value){ 
     if(preg_match($value, $this->agent)){ 
      $this->info = array_merge($this->info,array("Operating System" => $key)); 
      break; 
     } 
    } 
    return $this->info['Operating System']; 
} 

function getVersion($browser, $search, $string){ 
    $browser = $this->info['Browser']; 
    $version = ""; 
    $browser = strtolower($browser); 
    preg_match_all($search,$string,$match); 
    switch($browser){ 
     case "firefox": $version = str_replace("/","",$match[1][0]); 
     break; 

     case "internet explorer": $version = substr($match[1][0],0,4); 
     break; 

     case "opera": $version = str_replace("/","",substr($match[1][0],0,5)); 
     break; 

     case "navigator": $version = substr($match[1][0],1,7); 
     break; 

     case "maxthon": $version = str_replace(")","",$match[1][0]); 
     break; 

     case "google chrome": $version = substr($match[1][0],1,10); 
    } 
    return $version; 
} 

function showInfo($switch){ 
    $switch = strtolower($switch); 
    switch($switch){ 
     case "browser": return $this->info['Browser']; 
     break; 

     case "os": return $this->info['Operating System']; 
     break; 

     case "version": return $this->info['Version']; 
     break; 

     case "all" : return array($this->info["Version"], 
      $this->info['Operating System'], $this->info['Browser']); 
     break; 

     default: return "Unkonw"; 
     break; 

    } 
} 
}  


$obj = new OS_BR(); 

echo $obj->showInfo('browser'); 

echo $obj->showInfo('version'); 

echo $obj->showInfo('os'); 

echo "<pre>".print_r($obj->showInfo("all"),true)."</pre>"; 

?> 
2

User Agent può essere falsificato e il suo meglio non dipende dalla stringa dell'agente utente piuttosto che puoi utilizzare una query media CSS3 se vuoi solo rilevare l'orientamento (puoi esplorare il CSS del famoso bootstrap framework reattivo per verificare come puoi gestire la parte di orientamento usando CSS)

Qui è piccolo CSS:

@media only screen and (max-width: 999px) { 
    /* rules that only apply for canvases narrower than 1000px */ 
    } 

    @media only screen and (device-width: 768px) and (orientation: landscape) { 
    /* rules for iPad in landscape orientation */ 
    } 

    @media only screen and (min-device-width: 320px) and (max-device-width: 480px) { 
    /* iPhone, Android rules here */ 
    }  

Per saperne di più: About CSS orientation detection

o si può trovare l'orientamento utilizzando JavaScript:

// Listen for orientation changes 
    window.addEventListener("orientationchange", function() { 
     // Announce the new orientation number 
     alert(window.orientation); 
    }, false); 

Per saperne di più: About detect orientation using JS

Infine, se si vuole davvero andare con la stringa user agent allora questo codice aiutare molto, funziona bene su quasi tutti i browser:

<?php 
class BrowserDetection { 

    private $_user_agent; 
    private $_name; 
    private $_version; 
    private $_platform; 

    private $_basic_browser = array (
     'Trident\/7.0' => 'Internet Explorer 11', 
    'Beamrise' => 'Beamrise', 
    'Opera' => 'Opera', 
    'OPR' => 'Opera', 
    'Shiira' => 'Shiira', 
    'Chimera' => 'Chimera', 
    'Phoenix' => 'Phoenix', 
    'Firebird' => 'Firebird', 
    'Camino' => 'Camino', 
    'Netscape' => 'Netscape', 
    'OmniWeb' => 'OmniWeb', 
    'Konqueror' => 'Konqueror', 
    'icab' => 'iCab', 
    'Lynx' => 'Lynx', 
    'Links' => 'Links', 
    'hotjava' => 'HotJava', 
    'amaya' => 'Amaya', 
    'IBrowse' => 'IBrowse', 
    'iTunes' => 'iTunes', 
    'Silk' => 'Silk', 
    'Dillo' => 'Dillo', 
    'Maxthon' => 'Maxthon', 
    'Arora' => 'Arora', 
    'Galeon' => 'Galeon', 
    'Iceape' => 'Iceape', 
    'Iceweasel' => 'Iceweasel', 
    'Midori' => 'Midori', 
    'QupZilla' => 'QupZilla', 
    'Namoroka' => 'Namoroka', 
    'NetSurf' => 'NetSurf', 
    'BOLT' => 'BOLT', 
    'EudoraWeb' => 'EudoraWeb', 
    'shadowfox' => 'ShadowFox', 
    'Swiftfox' => 'Swiftfox', 
    'Uzbl' => 'Uzbl', 
    'UCBrowser' => 'UCBrowser', 
    'Kindle' => 'Kindle', 
    'wOSBrowser' => 'wOSBrowser', 
    'Epiphany' => 'Epiphany', 
    'SeaMonkey' => 'SeaMonkey', 
    'Avant Browser' => 'Avant Browser', 
    'Firefox' => 'Firefox', 
    'Chrome' => 'Google Chrome', 
    'MSIE' => 'Internet Explorer', 
    'Internet Explorer' => 'Internet Explorer', 
    'Safari' => 'Safari', 
    'Mozilla' => 'Mozilla' 
    ); 

    private $_basic_platform = array(
     'windows' => 'Windows', 
    'iPad' => 'iPad', 
     'iPod' => 'iPod', 
    'iPhone' => 'iPhone', 
    'mac' => 'Apple', 
    'android' => 'Android', 
    'linux' => 'Linux', 
    'Nokia' => 'Nokia', 
    'BlackBerry' => 'BlackBerry', 
    'FreeBSD' => 'FreeBSD', 
    'OpenBSD' => 'OpenBSD', 
    'NetBSD' => 'NetBSD', 
    'UNIX' => 'UNIX', 
    'DragonFly' => 'DragonFlyBSD', 
    'OpenSolaris' => 'OpenSolaris', 
    'SunOS' => 'SunOS', 
    'OS\/2' => 'OS/2', 
    'BeOS' => 'BeOS', 
    'win' => 'Windows', 
    'Dillo' => 'Linux', 
    'PalmOS' => 'PalmOS', 
    'RebelMouse' => 'RebelMouse' 
    ); 

    function __construct($ua = '') { 
     if(empty($ua)) { 
      $this->_user_agent = (!empty($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:getenv('HTTP_USER_AGENT')); 
     } 
     else { 
      $this->_user_agent = $ua; 
     } 
     } 

    function detect() { 
     $this->detectBrowser(); 
     $this->detectPlatform(); 
     return $this; 
    } 

    function detectBrowser() { 
    foreach($this->_basic_browser as $pattern => $name) { 
     if(preg_match("/".$pattern."/i",$this->_user_agent, $match)) { 
      $this->_name = $name; 
      // finally get the correct version number 
      $known = array('Version', $pattern, 'other'); 
      $pattern_version = '#(?<browser>' . join('|', $known).')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; 
      if (!preg_match_all($pattern_version, $this->_user_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($this->_user_agent,"Version") < strripos($this->_user_agent,$pattern)){ 
        @$this->_version = $matches['version'][0]; 
       } 
       else { 
        @$this->_version = $matches['version'][1]; 
       } 
      } 
      else { 
       $this->_version = $matches['version'][0]; 
      } 
      break; 
     } 
     } 
    } 

    function detectPlatform() { 
     foreach($this->_basic_platform as $key => $platform) { 
      if (stripos($this->_user_agent, $key) !== false) { 
       $this->_platform = $platform; 
       break; 
      } 
     } 
    } 

    function getBrowser() { 
     if(!empty($this->_name)) { 
      return $this->_name; 
     } 
    }   

    function getVersion() { 
     return $this->_version; 
    } 

    function getPlatform() { 
     if(!empty($this->_platform)) { 
      return $this->_platform; 
     } 
    } 

    function getUserAgent() { 
     return $this->_user_agent; 
    } 

    function getInfo() { 
     return "<strong>Browser Name:</strong> {$this->getBrowser()}<br/>\n" . 
     "<strong>Browser Version:</strong> {$this->getVersion()}<br/>\n" . 
     "<strong>Browser User Agent String:</strong> {$this->getUserAgent()}<br/>\n" . 
     "<strong>Platform:</strong> {$this->getPlatform()}<br/>"; 
    } 
} 

$obj = new BrowserDetection(); 

echo $obj->detect()->getInfo(); 

Il lavoro codice di cui sopra s per me quasi su ogni browser e spero che ti aiuterà un po '.

+1

oh ragazzo ma non sai nemmeno cosa vuole fare con quella informazione e vai a suggerire le domande dei media ... – user151496

Problemi correlati