wow
wow

Reputation: 8239

How to block some of http user agent using php

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

Answers (2)

Jeremy L
Jeremy L

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

karim79
karim79

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

Related Questions