How to block some of http user agent using php
-
20-09-2019 - |
Question
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?
Solution
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();
}
OTHER TIPS
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow