PHP 8 reference · String Functions
PHP hash() Function
Hash a string with the algorithm you choose, such as sha256, sha512, crc32b or xxh3. Returns a hex string.
PHP 8 Since 5.1
Syntax
hash(string $algo, string $data, bool $binary = false, array $options = []): string
Parameters
| Parameter | Description |
|---|---|
algo |
The algorithm name; hash_algos() lists them all. |
data |
The data to hash. |
binary optional |
true returns raw bytes. Default: false |
options optional |
Algorithm options, such as a seed for xxHash and MurmurHash. Default: [] |
Return value
The hash as a lowercase hex string.
Examples
<?php
echo hash("sha256", "hello"), "\n";
echo hash("crc32b", "hello"), "\n";
Output
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 3610a686
<?php
$secret = "server-side-key";
$sig = hash_hmac("sha256", "order=42&total=19.50", $secret);
echo strlen($sig), "\n";
var_dump(hash_equals($sig, hash_hmac("sha256", "order=42&total=19.50", $secret)));
Output
64 bool(true)
Version history
| Version | Change |
|---|---|
| PHP 5.1 | Added |
| PHP 8.1 | Added the options parameter and the xxHash and MurmurHash3 algorithms. |
Related
md5()· Calculate the MD5 hash of a string as 32 hex characters. Fine for checksums and cache keys, never for passwords.sha1()· Calculate the SHA-1 hash of a string as 40 hex characters. Weak for security; prefer hash("sha256", ...).base64_encode()· Encode binary data or text as Base64, using only letters, digits, + and /, so it travels safely as text.- PHP Strings · tutorial