Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

hash

Returns the hash of a string using a chosen algorithm.

Syntax

hash(string $algo, string $data): string

Parameters

ParameterTypeDescription
$algostringThe algorithm name: `sha256`, `sha512`, `crc32b` and others.
$datastringThe source string.

Return value

stringThe hash as a hexadecimal string.

Examples

SHA-256:

<?php
 
echo hash('sha256', 'hello');

Output:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

The length of a hash depends on the algorithm:

<?php
 
echo strlen(hash('sha256', 'a')), ' ', strlen(hash('sha512', 'a'));

Output:

64 128

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.