Jump to content

I don't understand this browser detection code.


silverglade

Recommended Posts

Hi, I came across this code that detects a user's browser and I don't understand parts of it. Here is the code below.

 

 $agent = $_SERVER['HTTP_USER_AGENT'];

if ( strpos(strtoupper($agent), 'MSIE')) {
print "Internet Explorer";
}
else if (strpos(strtoupper($agent), 'FIREFOX')) {
print "Firefox";
}
else if (strpos(strtoupper($agent), 'KONQUEROR')) {
print "Konqueror";
}
else if (strpos(strtoupper($agent), "LYNX")) {
print "Lynx";
}
else {
print $agent;
}

 

and here is the part I don't understand.

 

if ( strpos(strtoupper($agent), 'MSIE'))

 

I know that strtoupper makes all letters uppercase,

and that strpos returns the position of the string within

the larger string, but I don't know why they are in an if

statement.  Any help or explanation is greatly appreciated. Thanks. Derek

if strpos finds a match it will return the position of the first character which most of the time is > 0 ie. true

 

if any of the browser agents are at the start of the string the if statement will fail falsely.

 

i beleive in order to do that properly you need to do

 

if ( strpos(strtoupper($agent), 'MSIE') !== 0) {

 

to properly look for boolean false instead of zero/false.

 

Hope this makes sense.

The issue with strpos() returning 0 will only affect lynx, as the other browsers start their user agent with Mozilla, and have the real identifying info later.

 

silverglade, in php any number like 1, 2, 3 is considered as "true" for an "if".  So if strpos returns the position of a string, the "if" will succeed.  If strpos doesn't find the string then it returns false, which of course makes the "if" fail.  Is that the bit you were unsure of?

Ok thank you, now I understand why they used strpos. Now I don't understand why they used strtoupper though. lol. any more help greatly appreciated. thanks. sorry. :confused:

 

<?php if ( strpos(strtoupper($agent), 'MSIE'))?>

 

I don't know why they had to capitalize the result.

They used strtoupper() so they can match the string in any case.  You can use strtolower() the same way.  Eg

 

strtoupper('Lynx') == 'LYNX';
strtoupper('LyNX') == 'LYNX';
strtoupper('konqueror') == 'KONQUEROR';

 

So regardless of whether the string is upper or lowercase at the start, the strtoupper() makes sure it matches.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.