How to Create a Rate Limit System in PHP for Limiting Requests by IP: A Step-by-Step Guide

Tiempo de lectura: 2 minutos

Learn how to protect your PHP server from abuse, bots or brute-force attacks by limiting the number of requests per second from each IP address.

Camera reflex - pexels

The Rate Limiting (or rate limiting) is a technique that allows to restrict the number of requests that a user (or IP) can make to a server within a time period determined.

You use for:

In this tutorial you will learn how to create your own PHP rate limiting system using temporary files to store the requests.

The complete PHP code (copy and paste)

<?php // =========================================== // RATE LIMIT SYSTEM IN PHP // =========================================== // Get the real user IP address // If you use Nginx Proxy, 'HTTP_X_REAL_IP' returns the original IP $ip = $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR']; // Configure the request limit $maxRequests = 3; // Maximum number of requests allowed $window = 5; // Time window in seconds now = microtime(true); // Current time with microseconds // Define the path to the temporary file where previous requests are stored $rateLimitFile = sys_get_temp_dir() . '/rate_limit_' . md5($ip) . '.txt'; // Load previous requests (if exist) $requests = []; if (file_exists($rateLimitFile)) { $requests = json_decode(file_get_contents($rateLimitFile), true); if (!is_array($requests)) $requests = []; // Remove requests outside the time window $requests = array_filter($requests, function($t) use ($now, $window) { return ($now - $t) < $window; }); } // Add the new request to the list $requests[] = $now; // If the number of requests exceeds the maximum, return an error 429 if (count($requests) > $maxRequests) { http_response_code(429); header('Content-Type: application/json'); echo json_encode([ 'error' => 'Too many requests from this IP. Try again later.', 'ip' => $ip, 'limit' => $maxRequests, 'window_seconds' => $window ]); exit; } // Save the updated request list file_put_contents($rateLimitFile, json_encode($requests)); // If no limit was exceeded, continue normally header('Content-Type: application/json'); echo json_encode([ 'status' => 'OK', 'message' => 'Request accepted correctly.', 'ip' => $ip, 'requests_in_window' => count($requests) ]); 

Description:

Identify the user by IP.
Cada visitor identifies with their IP address.

Create a unique temporary file for each IP where timestamps of recent requests are stored.

Each time a request is made, recent timestamps are stored and old ones are removed.

If more than 3 requests in 5 seconds, the script returns the HTTP code 429 Too Many Requests and cuts off execution.

If no limit is exceeded, the response continues as normal.

You can use this script at the start of your endpoints or APIs in PHP, for example:

require 'rate_limit.php'; // include the script // Your main logic here echo "Hello, secure world";

Every time a user makes more than 3 requests in less than 5 seconds, the server will respond with an error message in JSON format.

Leave a Comment