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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.