PHP

Constant-Time String Compare

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Compare two strings in constant time to avoid timing-attack leaks when checking secrets like API keys, session tokens, or HMAC signatures. Always use hash_equals — never ===.
PHP
Raw
<?php
function safeCompare(string $expected, string $actual): bool {
    // hash_equals: O(strlen($expected)) regardless of where the strings differ.
    return hash_equals($expected, $actual);
}

// Don't do this (timing leak):
//   if ($_GET['api_key'] === $secret) { ... }   ❌

// Do this:
if (safeCompare($secret, $_GET['api_key'] ?? '')) {
    // authorized
} else {
    http_response_code(401);
    exit('Unauthorized');
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.