hash_equals
Compares two strings in constant time.
Syntax
hash_equals(string $known_string, string $user_string): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $known_string | string | The known value. |
| $user_string | string | The value received from the user. |
Return value
bool`true` if the strings are equal.
Examples
Checking a token:
<?php
$expected = 'a3f9c1';
var_dump(hash_equals($expected, 'a3f9c1'));
var_dump(hash_equals($expected, 'a3f9c2'));Output:
bool(true)
bool(false)Notes
A regular === stops at the first difference, so the value can be guessed from the response time. Compare tokens and signatures only with this function.
See also
- hash_hmac — Calculates a signature of data with a secret key.
- password_verify — Checks whether a password matches a hash.
- strcmp — Compares two strings.
Related recipes
In the tutorial
- Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.