Joe Black
Joe Black

Reputation: 13

PHP formula to prevent exceeding http requests from an IP

I am going to prevent hackers from scanning my website pages , I invented a formula to control average hits in a time span , is it the best solution?

function exceeded(){
  $limit=5;
  $span=15;
  $now=time();
  if($now-$_SESSION['lastDate']>=$span){
     $_SESSION['lastDate']=$now;
     $_SESSION['totalHits']=1;
     return false;
  }
  $_SESSION['totalHits']=($_SESSION['totalHits']*($span-($now-$_SESSION['lastDate'])))/$span;
  $_SESSION['totalHits']+=1; // Adds current Hit
  if($_SESSION['totalHits']<=$limit){
      $_SESSION['lastDate']=$now;
      return false;
   }
   $_SESSION['lastDate']=$now;
   return true;
}
//-----------------------------
if(exceeded()){
  echo 'You have exceeded your request limit come back in 15 seconds';
  exit;
}

Upvotes: 0

Views: 147

Answers (1)

Tom
Tom

Reputation: 433

You are still going to execute PHP code which needs CPU/RAM/... so a better way to do this is through limiting requests handled by the server. If you are afraid of a user DDoSing your server try using a service like Cloudflare.

If you are using Apache, read up onto mod_evasive, Nginx users can limit the rate requests get through.

Why PHP is also not a good choice? A DDoS tool will not storage cookies and this moment you are actually using the storage of your clients computer to remember his visits. If you really want to do it in PHP you should check on the users IP and use a database of his requests (which also takes CPU/RAM everytime he visits).

Upvotes: 1

Related Questions