How to enable DDoS protection?

前端 未结 10 1181
天命终不由人
天命终不由人 2020-11-29 15:04

DDoS (Distributed Denial of Service Attacks) are generally blocked on a server level right?

Is there a way to block it on a PHP level, or at least reduce it?

10条回答
  •  -上瘾入骨i
    2020-11-29 15:35

    How about something like this on PHP side:

    //if user does not change IP, then ban the IP when more than 10 requests per second are detected in 1 second
    $limitps = 10;
    if (!isset($_SESSION['first_request'])){
        $_SESSION['requests'] = 0;
        $_SESSION['first_request'] = $_SERVER['REQUEST_TIME'];
    }
    $_SESSION['requests']++;
    if ($_SESSION['requests']>=10 && strtotime($_SERVER['REQUEST_TIME'])-strtotime($_SESSION['first_request'])<=1){
        //write the IP to a banned_ips.log file and configure your server to retrieve the banned ips from there - now you will be handling this IP outside of PHP
        $_SESSION['banip']==1;
    }elseif(strtotime($_SERVER['REQUEST_TIME'])-strtotime($_SESSION['first_request']) > 2){
        $_SESSION['requests'] = 0;
        $_SESSION['first_request'] = $_SERVER['REQUEST_TIME'];
    }
    
    if ($_SESSION['banip']==1) {
        header('HTTP/1.1 503 Service Unavailable');
        die;
    }
    

提交回复
热议问题