Verify an HMAC signature in PHP (constant time)
Check a webhook or signed-request HMAC with hash_hmac and hash_equals to avoid timing attacks.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?php
function verifySignature(string $rawBody, string $signatureHex, string $secret): bool
{
$expected = hash_hmac('sha256', $rawBody, $secret);
return hash_equals($expected, strtolower($signatureHex));
}How it works
Compute the HMAC over the raw request body (not re-encoded JSON) with your shared secret, then compare with hash_equals, which takes the same time regardless of where the strings differ. Plain === can leak information through timing.
Also check a timestamp inside the signed payload and reject old requests to limit replay attacks. Read the raw body with file_get_contents('php://input').
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- Python Tested
Sign API requests with HMAC-SHA256
Create and verify a timestamped signature over the method, path and body so requests cannot be forged or replayed.
- JavaScript Tested
Generate secure random IDs and integers
Create UUIDs, random integers in a range and URL-safe tokens with the Web Crypto API instead of Math.random.
- PHP Tested
Generate a secure random token in PHP
Create unpredictable tokens for password resets, API keys and CSRF protection with random_bytes.

