I have a simple script, in which I am trying to pull the browser type out of an agent string. This should be horribly easy but I cant seem to pull it off.
I am using regex, and have tried a dizzying array of different configurations. The only response I am getting from the script is the default case, that being unknown. In using my own user agent string, I know the word Firefox is within the string but cant capture it.
Code:
$agent = $_SERVER["HTTP_USER_AGENT"];
if (isset($agent)){
switch($agent){
case 1:
if (preg_match('/(?:MSIE 3)/', $agent)){
$browser = "MSIE 3";
}break;
case 2:
if (preg_match('/(?:MSIE 4)/', $agent)){
$browser = "MSIE 4";
}break;
case 3:
if (preg_match('/(?:MSIE 5)/', $agent)){
$browser = "MSIE 5";
} break;
case 4:
if (preg_match('/(?:MSIE 6)/', $agent)){
$browser = "MSIE 6";
}break;
case 5:
if (preg_match('/(?:MSIE 7)/', $agent)){
$browser = "MSIE 7";
}break;
case 6:
if (preg_match('/?:(MSIE 8)/', $agent)){
$browser = "MSIE 8";
} break;
case 7:
if (preg_match('/(?:Opera)/', $agent)){
$browser = "Opera";
}break;
case 8:
if (preg_match('/(?:Chrome)/', $agent)){
$browser = "Chrome";
}break;
case 9:
if (preg_match('/(?:Safari)/', $agent)){
$browser = "Safari";
}break;
case 10:
if (preg_match('/^(?:(Firefox))$/', $agent)){
$browser = "Firefox";
}break;
default:
$browser = "Unknown";
}
}
I have tried the break within the if statement and outside. The script from here just goes on to enter the browser into the database.
Looks like a misunderstanding of the "case" part of a switch(). case 1: is testing if $agent == 1. Since it does not, it goes to the next case, and so on until you reach the default. Also, you don't want to anchor the "Firefox" to the start (^) and end ($) of the regexp. Lastly, by definition $agent is always set since you define it right before you do the isset(). So, here's a shortened piece of code that correctly identified by Firefox browser string:
case preg_match('/Firefox/', $agent):
$browser = "Firefox";
break;
default:
$browser = "Unknown";
}
echo $browser;
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks