A hash is a short fixed-length fingerprint of some data. The same data always gives the same hash, a tiny change gives a very different one, and you cannot turn a hash back into the original. In PHP you create one with hash().
Hashes are used to check that a file was not changed, to sign messages with a secret key (hash_hmac()), to build cache keys, and to derive keys from secrets. For large or streamed data you can hash in pieces with hash_init(), hash_update() and hash_final().
This page explains the ideas. The Hash Functions index lists all fifteen function guides.
Pick the right tool.
Use hash() for fingerprints, hash_hmac() when you need a secret key, hash_equals() to compare, and password_hash() for passwords.
Hashes are not passwords storage.
A plain hash is fast, so attackers can test billions of guesses. Use password_hash() for passwords.
Compare with hash_equals().
A normal == can leak timing information. Use hash_equals() for tokens, signatures and hashes.
Syntax
PHP Syntax
The usual pattern: pick an algorithm, hash the data, compare safely:
PHP
// A fingerprint of a string
$digest = hash('sha256', 'hello');
// A keyed signature
$mac = hash_hmac('sha256', $message, $secretKey);
// A fingerprint of a file
$fileHash = hash_file('sha256', $path);
// Hash in pieces
$ctx = hash_init('sha256');
hash_update($ctx, 'Hello, ');
hash_update($ctx, 'World');
$digest = hash_final($ctx);
// Safe comparison
if (hash_equals($expected, $received)) {
echo 'Valid';
}
A hash is a fixed-length fingerprint of some data, made with a function like hash(). The same input always gives the same hash and you cannot reverse it.
sha256 is a good default. Use sha512 for a longer hash. Avoid md5 and sha1 when security matters.
hash() has no key, so anyone can recompute it. hash_hmac() uses a secret key, so only the key holder can create or check the value.
A normal comparison stops at the first difference, which can leak timing information. hash_equals() takes the same time every time.
No. Plain hashes are too fast. Use password_hash() and password_verify(), which add a salt and are slow on purpose.
Use hash_file(). It reads the file in chunks, so memory use stays low. For several files or mixed data, use hash_init() with hash_update_file().