PHP Hash

Beginner
8 min read
Updated: Nov 2026
3 examples
hash(), HMAC & keys

Definition and Usage

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.

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';
}

Core Ideas

What to remember about each function:

IdeaFunctionRemember
Hash a stringhash()Algorithm first, data second. Returns hex by default.
Hash a filehash_file()Reads in chunks, so big files are fine.
Sign with a keyhash_hmac(), hash_hmac_file()Only the key holder can create the value.
Hash in pieceshash_init(), hash_update(), hash_final()Start, add data, then finish. A finished context cannot be reused.
Add files and streamshash_update_file(), hash_update_stream()Add file or stream contents to a context.
Branch a contexthash_copy()Clone a context to share a common start.
Derive keys{{hash-pbkdf2|hash_pbkdf2()}}, hash_hkdf()PBKDF2 for passwords, HKDF for strong keys.
Compare safelyhash_equals()Timing-safe. Trusted value first, user value second.
List algorithmshash_algos(), hash_hmac_algos()Check that a name is supported before you use it.

Choosing an Algorithm

The algorithm name is the first argument of most hash functions. Pick by what you need.

AlgorithmLength (hex)Use it for
sha25664General fingerprints, signatures and integrity checks. A good default.
sha512128When you want a longer hash.
md5, sha132, 40Old checksums only. Not safe against attackers.
crc32b8Fast error detection. Not for security.
Not for passwords.

None of these are right for storing passwords. Use password_hash().

PHP Examples

Three short scripts. The output is the same every time you run them.

Example 1 — A Fingerprint and a Signature

hash() needs no key. hash_hmac() adds a secret key.

PHP
<?php
echo hash('sha256', 'hello'), PHP_EOL;
echo hash_hmac('sha256', 'hello', 'secret-key'), PHP_EOL;
hash() Tutorial

How It Works

  1. Call `hash()`. Anyone can recompute this value.
  2. Call `hash_hmac()`. It needs the secret key.
  3. Compare the results. The same message gives two different values.
  4. Choose by purpose. Fingerprint or signature.

Example 2 — Hash in Pieces

Adding data in parts gives the same hash as hashing it all at once.

PHP
<?php
$ctx = hash_init('sha256');
hash_update($ctx, 'Hello, ');
hash_update($ctx, 'World');

echo "Same as hash(): ", hash_final($ctx) === hash('sha256', 'Hello, World') ? "yes" : "no", PHP_EOL;

How It Works

  1. Start with `hash_init()`. It returns a context.
  2. Add two parts with `hash_update()`. Order matters.
  3. Finish with `hash_final()`. You get the hash.
  4. Compare. It equals one hash() call.

Example 3 — Check a Signature Safely

Sign a message, then check what was received.

PHP
<?php
$secret = 'demo-secret';
$sent   = hash_hmac('sha256', 'order=1042', $secret);

foreach (['order=1042', 'order=9999'] as $received) {
    $expected = hash_hmac('sha256', $received, $secret);
    echo $received, ": ", hash_equals($sent, $expected) ? "valid" : "tampered", PHP_EOL;
}

How It Works

  1. Sign the original message. Save the signature.
  2. Recompute for each received message. Use the same key.
  3. Compare with `hash_equals()`. It is timing-safe.
  4. Reject changed data. Its signature differs.

Next: PHP Hash Functions Index

After you know hashing, HMAC and safe comparison, open the functions index for all fifteen guides.

Start withWhy
hash()Create a hash of a string
hash_hmac()Sign data with a secret key
hash_file()Hash a file's contents
hash_init()Start hashing large or streamed data in pieces
hash_equals()Compare hashes and tokens without timing leaks
{{hash-pbkdf2|hash_pbkdf2()}}Derive a key from a password

Full list: PHP Hash Functions index (/php/hash/function).

Frequently Asked Questions

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().

Browse every Hash function

Open the functions index for guides with examples and FAQs.

Hash Functions Index →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful