dongxixia6399 2016-09-27 08:51
浏览 65
已采纳

php - Antiflood - 如何限制每秒2个请求

I have an anti flood function,

if (!isset($_SESSION)) {
    session_start();
}

if($_SESSION['last_session_request'] > time() - 1){
die();
}

$_SESSION['last_session_request'] = time();

If user requests more than 1 request in 1 second, script stops itself. What I want to do is, I need to allow 2 requests per second maximum (instead of 1). How can I do that ?

  • 写回答

1条回答 默认 最新

  • douyan1321 2016-09-27 08:59
    关注

    I would do it this way:

    <?
    $time_interval = 1;#In seconds
    $max_requests = 2;
    $fast_request_check = ($_SESSION['last_session_request'] > time() - $time_interval);
    
    if (!isset($_SESSION)) 
    {
        # This is fresh session, initialize session and its variables
        session_start();
        $_SESSION['last_session_request'] = time();
        $_SESSION['request_cnt'] = 1;
    }
    elseif($fast_request_check && ($_SESSION['request_cnt'] < $max_requests))
    {
       # This is fast, consecutive request, but meets max requests limit
       $_SESSION['request_cnt']++;
    }
    elseif($fast_request_check)
    {
        # This is fast, consecutive request, and exceeds max requests limit - kill it
        die();
    }
    else
    {
        # This request is not fast, so reset session variables
        $_SESSION['last_session_request'] = time();
        $_SESSION['request_cnt'] = 1;
    }
    

    One thing, though - it will not protect You from DDoS attacks, if You are trying to do this king of thing. Session in PHP can be easily dropped, and even if not, multiple sessions can be created from one client. Read this discussion if You want to know more about protection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?