How to implement rate limiting in PHP to prevent DDoS attacks?

Member

by deron , in category: PHP Security , 2 years ago

How to implement rate limiting in PHP to prevent DDoS attacks?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a year ago

@deron 

There are several ways to approach rate limiting in PHP to prevent DDoS attacks. Here's one example:

  1. Determine the maximum number of requests allowed per time period (e.g., 10 requests per second).
  2. Create a PHP script that records the time and IP address of each incoming request.
  3. Check if the IP address has exceeded the maximum number of requests within the time period. If it has, return an error message or redirect to a page with a captcha.
  4. If the IP address has not exceeded the limit, record the new request and continue to process the request normally.


Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// Maximum number of requests allowed per second
$max_requests = 10;

// Time period in seconds
$time_period = 1;

// Get the client's IP address
$client_ip = $_SERVER['REMOTE_ADDR'];

// Check if the IP address has exceeded the limit
$requests = apc_fetch($client_ip);
if ($requests === false) {
  // New IP address, create a new entry
  $requests = array(time());
} else {
  // Remove expired requests
  $valid_requests = array();
  foreach ($requests as $request_time) {
    if (time() - $request_time <= $time_period) {
      $valid_requests[] = $request_time;
    }
  }
  $requests = $valid_requests;

  // Check if the IP address has exceeded the limit
  if (count($requests) >= $max_requests) {
    header('HTTP/1.1 429 Too Many Requests');
    header('Content-Type: text/plain');
    echo 'Rate limit exceeded';
    exit();
  }

  // Add the new request
  $requests[] = time();
}

// Save the revised request list
apc_store($client_ip, $requests);


This implementation uses the APC extension to store the request times in memory. You can modify it to use a database or file system for persistence if desired. Note that this is just one of many possible approaches to rate limiting in PHP, and may need to be adjusted or combined with other techniques to fully protect against DDoS attacks.