Simple PHP Rate Limiter for API Endpoints

By: Paypal August 4, 2025 Security

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()];
    }
}

Discussion (0)