I found this method on stack overflow which works very good
$badAgents = array('fooAgent','blahAgent', 'etcAgent');
if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) {
exit();
}
BUT
the problem is that the string needs to be perfectly match to the string inside the array.
I need to came with a new method that will ask if the user agent contains (in any part of the string) one of the strings inside the array (not exactly match just ask if it contains ONE of the characters/words inside several options inside the array)... so I came up with this :
$badAgents = array('google','libwww');
if (strpos(in_array(strtolower($_SERVER['HTTP_USER_AGENT']))), $badAgents) == true) {
exit();
}
It's not working but I assume this it will work with small tweak.
Thanks a lot in advance guys!
In general, best practice is to use feature detection rather than user agent switching.
However, in this case, it seems that your parentheses placement is off. Also, I rewrote the equality to make it more clear (since some values may evaluate to FALSE).
if (strpos(in_array(strtolower($_SERVER['HTTP_USER_AGENT'])), $badAgents) !== FALSE) {
exit();
}
I cannot comment so need to post this as an answer. Please note the warning on strpos http://php.net/manual/en/function.strpos.php The above code will not work as expected when the position of the string is 0 (beginning of the string).
Also the code is broken even further. You cannot do strpos on result of in_array (boolean).
Only way I see is iterating over the array and doing strpos for each element (assuming bad agents array consists of sub-strings to look for).
Updated example:
$badAgents = array('google','libwww','chrome');
$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
foreach($badAgents as $badAgent)
{
if (strpos($userAgent, $badAgent) !== false)
{
exit();
}
}
Runnable example:
<?php
$badAgents = array('google','libwww','chrome');
//$userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
$userAgent = strtolower('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11');
foreach($badAgents as $badAgent)
{
if (strpos($userAgent, $badAgent) !== false)
{
exit();
}
}
Also even though less clear at first get_browser() is a better and cleaner route (as suggested by Steven Liao)
The problem is that in_array checks for an EXACT match.
If you want to check if the string is contained you can iterate for each element in array:
foreach ($badAgents as $bad_user_agent) {
if (stripos($_SERVER['HTTP_USER_AGENT'], $bad_user_agent) !== false) {
exit();
}
}
P.S. Notice that I used stripos
that is case insensitive