duanjia7912 2019-07-12 16:12
浏览 28
已采纳

如何正确检查用户代理在php中是否为空

I want to ensure that my site users are only using chrome and firefox. My hosting company reported unnecessary hit to my site by users coming with empty user agent. This not DOS Attack.

I just want to block all users with empty user agents.

currently the code checks and ensure that only firefox and chrome broswers can access my site.

My question is how do I check users with empty useragent. This is my check for that. Is it right?

//check if useragent is empty
if($agent==''){
echo "user agent is empty. access block";
}

below is the code so far which ensures that only firefox and chrome are allowed access

$arr_browsers = ["Firefox", "Chrome"];
$agent = $_SERVER['HTTP_USER_AGENT'];

$user_browser = '';
foreach ($arr_browsers as $browser) {
    if (strpos($agent, $browser) !== false) {
        $user_browser = $browser;
        break;
    }   
}


//check if the browser is not in array

if ( ! ( in_array($user_browser, $arr_browsers) ) ) {

echo "you browser are not allowed. This work fine";

}
  • 写回答

1条回答 默认 最新

  • doulue7522 2019-07-12 16:19
    关注

    Your test for an empty user agent looks fine to me.

    In the second code, there's no need to check if $user_agent is in the array. If it's not the empty string that you initialize it with, it must be one of the values from the array. So just write

    if ($user_browser == '') {
        echo "your browser is not allowed";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?