Simple PHP Rate Limiter for API Endpoints
Description
A lightweight PHP snippet to limit the number of API requests per IP address to prevent abuse or DDoS attacks.
Code Snippet
$ip = $_SERVER['REMOTE_ADDR'];
$limit = 100; // requests
$timeframe = 3600; // seconds
session_start();
if (!isset($_SESSION['hits'][$ip])) {
$_SESSION['hits'][$ip] = ['count' => 1, 'start' => time()];
} else {
if (time() - $_SESSION['hits'][$ip]['start'] < $timeframe) {
$_SESSION['hits'][$ip]['count']++;
if ($_SESSION['hits'][$ip]['count'] > $limit) {
die('Rate limit exceeded.');
}
} else {
$_SESSION['hits'][$ip] = ['count' => 1, 'start' => time()];
}
}