How To Create A Rate Limiter Module In PHP

Rate limiter module in PHP that allows you to limit the number of requests per minute:


class RateLimiter
    private $storage;
    private $requestsPerMinute;

    public function __construct($storage, $requestsPerMinute)
        $this->storage = $storage;
        $this->requestsPerMinute = $requestsPerMinute;

    public function limitRequests()
        $ip = $this->getClientIP();
        $key = $this->generateKey($ip);

        $requests = $this->storage->get($key);
        if (!$requests) {
            $requests = 0;

        $this->storage->set($key, $requests, 60);

        if ($requests > $this->requestsPerMinute) {
            // Request limit exceeded
            exit('Too Many Requests');

    private function getClientIP()
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return $_SERVER['REMOTE_ADDR'];

    private function generateKey($ip)
        return 'rate_limit:' . $ip;

In this example, the RateLimiter class takes two parameters: $storage and $requestsPerMinute. The $storage parameter represents the storage mechanism (e.g., Redis, Memcached) used to store and retrieve the request counts for each IP address. The $requestsPerMinute parameter defines the maximum number of requests allowed per minute.

The limitRequests() method is called to check and limit the number of requests. It retrieves the client’s IP address, generates a key based on the IP address, and retrieves the current request count from the storage. If the request count exceeds the defined limit, a 429 Too Many Requests response is sent, indicating that the request limit has been exceeded.

You would need to customize the storage mechanism ($storage) based on your application’s requirements. This example assumes you have a storage implementation that provides methods to get and set values with an expiration time.

To use the rate limiter, you can include the RateLimiter class in your PHP files and invoke the limitRequests() method before processing the actual request. For example:


$storage = new RedisStorage(); // Customize this based on your storage mechanism
$rateLimiter = new RateLimiter($storage, 60); // Allow 60 requests per minute


// Continue with your application logic...

Please note that this is a basic example of a rate limiter module, and you may need to customize it further based on your specific requirements, such as handling different time intervals, implementing more sophisticated storage mechanisms, or applying rate limiting to specific routes or user roles.