hash_hmac
Calculates a signature of data with a secret key.
Syntax
hash_hmac(string $algo, string $data, string $key, bool $binary = false): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $algo | string | The algorithm, such as `sha256`. |
| $data | string | The data to sign. |
| $key | string | The secret key. |
| $binary | bool | Optional. `true` returns raw bytes. |
Return value
stringThe signature in hexadecimal.
Examples
Signing and verifying:
<?php
$secret = 'my-secret-key';
$payload = '{"order":42}';
$signature = hash_hmac('sha256', $payload, $secret);
var_dump(hash_equals($signature, hash_hmac('sha256', $payload, $secret)));
var_dump(hash_equals($signature, hash_hmac('sha256', '{"order":43}', $secret)));Output:
bool(true)
bool(false)Notes
This is how you check that a request from a payment system or another service is not forged. Compare signatures only with hash_equals().
See also
- hash — Returns the hash of a string using a chosen algorithm.
- hash_equals — Compares two strings in constant time.
- random_bytes — Returns cryptographically secure random bytes.
In the tutorial
- Security — The basics of PHP site security — XSS and escaping, SQL injection, password hashing, CSRF tokens and validating input.