hash_equals()
hash_equals() — Timing attack safe string comparison.
Built-in function of PHP 8.5. The manual lists it as available in PHP 5 >= 5.6.0, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Checks whether two strings are equal without leaking information about the contents of known_string via the execution time.
Signature
hash_equals(string $known_string, string $user_string): bool
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $known_string | string | The known string that must be kept secret. |
| $user_string | string | The user-supplied string to compare against. |
Return value
Returns true when the two strings are equal, false otherwise.
Example
A runnable snippet:
$secretKey = '8uRhAeH89naXfFXKGOEj'; // Value and signature are provided by the user, e.g. within the URL // and retrieved using $_GET. $value = 'username=rasmuslerdorf'; $signature = '8c35009d3b50caf7f5d2c1e031842e6b7823a1bb781d33c5237cd27b57b5f327'; if (hash_equals(hash_hmac('sha256', $value, $secretKey), $signature)) { echo "The value is correctly signed.", PHP_EOL; } else { echo "The value was tampered with.", PHP_EOL; }
Output:
The value is correctly signed.
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page hash_equals() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.