Implementing Signature and Rate‑Limiting Mechanisms for Secure PHP APIs
This article explains how to protect PHP‑based API endpoints by using request signatures, nonce and timestamp validation, Redis‑backed rate limiting, and additional best practices such as HTTPS, access control, input validation, logging, and security audits.
In modern applications, APIs are widely exposed, making them attractive targets for attackers; securing them requires mechanisms such as request signing and rate limiting.
Signature mechanism: the client builds a signature using a secret key, timestamp, nonce and request data, then sends it with the request; the server recomputes the signature and compares it to verify integrity and authenticity.
Example client code (PHP):
// client request data
$data = array(
'name' => 'John Smith',
'email' => '[email protected]',
'phone' => '1234567890',
);
$timestamp = time();
$nonce = uniqid();
$signature = sha1($secret_key . $timestamp . $nonce . json_encode($data));
$url = 'http://example.com/api';
$data['timestamp'] = $timestamp;
$data['nonce'] = $nonce;
$data['signature'] = $signature;
$response = http_post($url, $data);
// handle responseServer‑side code validates the request, enforces a per‑IP rate limit using Redis, checks timestamp freshness, ensures the nonce has not been reused, and verifies the signature before processing the payload.
$ip_address = $_SERVER['REMOTE_ADDR'];
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// get request count in last 60 seconds
$count = $redis->get($ip_address);
if ($count === false) {
$redis->setex($ip_address, 60, 1);
} else {
$redis->incr($ip_address);
$count = $redis->get($ip_address);
if ($count > 10) {
die("Too many requests");
}
}
$timestamp = $_POST['timestamp'];
$nonce = $_POST['nonce'];
$signature = $_POST['signature'];
$data = $_POST['data'];
if (time() - $timestamp > 60) {
die("Timestamp expired");
}
if (in_array($nonce, $used_nonces)) {
die("Nonce already used");
} else {
$used_nonces[] = $nonce;
}
$expected_signature = sha1($secret_key . $timestamp . $nonce . $data);
if ($signature != $expected_signature) {
die("Invalid signature");
}
// process request dataAdditional best practices include using HTTPS, enforcing access control, validating all inputs, logging requests, and performing regular security audits to further harden API endpoints.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
