doucheng7808 2013-08-08 01:36
浏览 22

通过PHP阻止或重定向坏用户代理或机器人

I found this method on stack overflow which works very good

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

BUT

the problem is that the string needs to be perfectly match to the string inside the array.

I need to came with a new method that will ask if the user agent contains (in any part of the string) one of the strings inside the array (not exactly match just ask if it contains ONE of the characters/words inside several options inside the array)... so I came up with this :

$badAgents = array('google','libwww');

if (strpos(in_array(strtolower($_SERVER['HTTP_USER_AGENT']))), $badAgents) == true) {
    exit();
}

It's not working but I assume this it will work with small tweak.

Thanks a lot in advance guys!

  • 写回答

3条回答 默认 最新

  • douye2036 2013-08-08 01:40
    关注

    In general, best practice is to use feature detection rather than user agent switching.

    However, in this case, it seems that your parentheses placement is off. Also, I rewrote the equality to make it more clear (since some values may evaluate to FALSE).

    if (strpos(in_array(strtolower($_SERVER['HTTP_USER_AGENT'])), $badAgents) !== FALSE) {
        exit();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大