[ACCEPTED]-How to block some of http user agent using php-user-agent

Accepted answer
Score: 13

I like @Nerdling's answer, but in case it's 3 helpful, if you have a very long list of 2 user agents that need to be blocked:

$badAgents = array('fooAgent','blahAgent', 'etcAgent');
foreach($badAgents as $agent) {
    if(strpos($_SERVER['HTTP_USER_AGENT'],$agent) !== false) {
        die('Go away');
    }
}

Better 1 yet:

$badAgents = array('fooAgent','blahAgent', 'etcAgent');
if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) {
    exit();
}
Score: 2

You should avoid using regex for this as 4 that will add a lot of resources just to 3 decide to block a connection. Instead, just 2 check to see if the string is there with 1 strpos()

if (strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 1") !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 2") !== false
 || strpos($_SERVER['HTTP_USER_AGENT'], "Agent Name 3") !== false) {
    exit;
}

More Related questions