hash
Returns the hash of a string using a chosen algorithm.
Syntax
hash(string $algo, string $data): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $algo | string | The algorithm name: `sha256`, `sha512`, `crc32b` and others. |
| $data | string | The source string. |
Return value
stringThe hash as a hexadecimal string.
Examples
SHA-256:
<?php
echo hash('sha256', 'hello');Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824The length of a hash depends on the algorithm:
<?php
echo strlen(hash('sha256', 'a')), ' ', strlen(hash('sha512', 'a'));Output:
64 128Notes
hash_hmac() signs data with a secret key, and hashes should be compared with hash_equals() — it protects against timing attacks.
See also
- md5 — Returns the MD5 hash of a string.
- password_hash — Creates a password hash for storing in a database.
- 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.