tags:

views:

411

answers:

2

Hi.. there have a way to block some of user agent via php script? Example on mod_security

SecFilterSelective HTTP_USER_AGENT "Agent Name 1"
SecFilterSelective HTTP_USER_AGENT "Agent Name 2"
SecFilterSelective HTTP_USER_AGENT "Agent Name 3"

Also we can block them using htaccess or robots.txt by example but I want in php. Any example code?

+2  A: 

You should avoid using regex for this as that will add a lot of resources just to decide to block a connection. Instead, just check to see if the string is there with 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;
}
Nerdling
Why do you think that using a regexp "will add a lot of resources"?
Michael Borgwardt
Because PHP's web site says so.
Nerdling
You should use strpos( $str ) !== false, since the substring could be positioned at index 0, and the test > 0 would fail. There's a note on the strpos() page specifically regarding type testing.
Rob
+6  A: 

I like @Nerdling's answer, but in case it's helpful, if you have a very long list of 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 yet:

$badAgents = array('fooAgent','blahAgent', 'etcAgent');
if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) {
    exit();
}
karim79
Nice but hopefully he's not blocking that many user agents!
Nerdling
Regardless, with anything above 2 user agents this would be the preferred method.
Daniel
bravoo! a better yet work as I wanted.
bob
@bob - LOL!!
karim79
Yes.. Better yet working fine, just tested with http://chrispederick.com/work/user-agent-switcher/ thanks karim.
bob