Detect browser and display

Want to detect the browser the user is using? This should help.

<?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;
?>

Wrong

OnkelTem - July 13, 2008 - 12:27

This code is wrong.
strpos returns 0 if string in 0-position and false if string not found.
Read PHP man

Wrong Code

sysipheantaskmaster - August 10, 2008 - 22:53

I'm PHP illiterate (trying to learn, just hard-headed I guess). Anyway, could you post the corrected code please? Thanks!

Correct Code

Solenoid - August 26, 2008 - 08:31

The code is actually correct.

OnkelTem would be correct if what was being searched for were at the start of $_SERVER['HTTP_USER_AGENT'] but it is not in this case.

If you are going to use this to do your own searches on strings where the search term could exist at the start of the string, strpos() could return 0, which equates to false. If you change all of the conditions to:
if (strpos(...) === true)
then it could be used for searching on any strings. And yes, there is meant to be three equal signs. Read up on php.net about strpos and Booleans if you are still confused.

A php function that you might also find useful is the get_browser function (http://au.php.net/manual/en/function.get-browser.php)

After outputting

Solenoid - August 26, 2008 - 09:12

After outputting $_SERVER['HTTP_USER_AGENT'] in my browsers for my own testing, I found that Opera does actually put it's name at the start (but also does not include 'MSIE'), meaning that this code is actually incorrect. Here is the correct code (including a search for Safari)

<?php
if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') )
{
  
$browser = 'Safari';
}
else 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') )
{
  
$browser = 'Internet Explorer (MSIE/Compatible)';
}
else if (
strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === true)
{
  
$browser = 'Opera';
}
else
{
  
$browser = 'Other browsers';
}

echo
$browser;
?>

 
 

Drupal is a registered trademark of Dries Buytaert.