Drupal DDoS Prevention Code

// The following code will ensure that there are no more than 30 non-cached requests in 60 seconds.
// Please adjust the first two variables below in a manner optimal to your server config.

// Note that this only protects heavier non cached pages.
// A powerful enough attack can even overload your server with requests for cached pages.

function hook_init()
{
    $MinTime = 60;
    $MaxAttmpts = 30;

    $MyAppDDoSCheckUrl = variable_get('MyAppDDoSCheckUrl');
    $TimeCheckNow = time();

    if ($MyAppDDoSCheckUrl == '')
    {
        variable_set('MyAppDDoSCheckUrl',$TimeCheckNow.',1');
        return;
    }

    $SerDDosVars = explode(',',$MyAppDDoSCheckUrl);
    $TimeLast = intval($SerDDosVars[0]);
    $ReqAttmt = intval($SerDDosVars[1]);
   
    if ((($TimeCheckNow - $TimeLast) < $MinTime) && ($ReqAttmt > $MaxAttmpts))
    {
        header('HTTP/1.1 503 Server busy, try again later');
        die('The server is currently overloaded. Please try again in a couple of minutes. Thank you!');
    }
    else if (($TimeCheckNow - $TimeLast) < $MinTime)
    {
        $ReqAttmt++;
        variable_set('MyAppDDoSCheckUrl',$TimeLast.','.$ReqAttmt);
    }
    else
    {
        variable_del('MyAppDDoSCheckUrl');
    }
}

Comments