PHP Code Examples

Implement a Basic Rate Limit in PHP with MySQL

Track request counts in a database to limit repeated actions such as login attempts or expensive API calls.

Example table

CREATE TABLE rate_limits (
    rate_key CHAR(64) PRIMARY KEY,
    window_started_at DATETIME NOT NULL,
    request_count INT UNSIGNED NOT NULL
) ENGINE=InnoDB;

Application approach

<?php
$identity = $userId
    ? 'user:' . $userId
    : 'ip:' . ($_SERVER['REMOTE_ADDR'] ?? 'unknown');

$key = hash('sha256', 'login:' . $identity);
$limit = 10;
$windowSeconds = 300;

// In production, perform this update atomically in a transaction
// or with a single SQL statement designed for your MySQL version.
$stmt = $pdo->prepare(
    'SELECT window_started_at, request_count
     FROM rate_limits WHERE rate_key = :key'
);
$stmt->execute(['key' => $key]);
$record = $stmt->fetch();

// Apply an atomic insert/update or transaction here, then reject
// requests whose count exceeds the configured limit.

Important

This is a schema and flow illustration, not a complete atomic limiter. A production limiter must increment counters atomically, define window-reset behavior, and use a trusted client-IP strategy behind proxies. Redis is often a better fit for high-volume rate limiting.

Share this page Help other developers discover this resource.