Reputation: 8239
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?
Upvotes: 3
Views: 8336
Reputation: 7797
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;
}
Upvotes: 2
Reputation: 342635
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();
}
Upvotes: 14