How to block part of HTTP agent using php

is there a way to block some user agent via php script? Mod_security example

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 for example, but I want php. Any sample code?

+2


source to share


2 answers


I like @ Nerdling's answer, but in case it is useful 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:

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

      

+11


source


You should avoid using regular expressions for this, as it will add a lot of resources to decide to block the connection. Instead, just check if there is a line 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;
}

      

+2


source







All Articles