How to block some of http user agent using php

笑着哭i 提交于 2019-12-06 08:42:51

问题


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?


回答1:


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();
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/1357983/how-to-block-some-of-http-user-agent-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!