Codectionary / Developer documentation / PHP

PHP timing-safe token comparison

hash_equals compares two strings while avoiding content-dependent timing for equal-length inputs. It is suited to comparing a known token or digest with a supplied value.

Syntax

hash_equals($known, $supplied)

Examples

PHP timing-safe token comparison

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$known = hash('sha256', 'example-token');
$supplied = hash('sha256', 'example-token');
echo hash_equals($known, $supplied) ? 'match' : 'different', PHP_EOL;
echo hash_equals($known, hash('sha256', 'other')) ? 'match' : 'different', PHP_EOL;
  1. Output: match, then different. These fixed strings demonstrate comparison; they are not a token generation scheme.

Best practices

  • Pass the known secret as the first argument and the user value second. Different lengths fail immediately; use password_verify for stored password hashes.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading