md5()
Our article is about the PHP function md5(), which is used to calculate the MD5 hash of a string. This function is useful for working with strings in PHP. In
The PHP md5() function calculates the MD5 hash of a string. MD5 (Message-Digest Algorithm 5) is a one-way function: it turns any input into a fixed 128-bit value, and you cannot reverse the result back to the original string. This page covers the syntax, the parameters, runnable examples, where MD5 is still appropriate, and where you must use something safer instead.
Syntax
md5(string $str, bool $raw_output = false): stringThe function accepts two parameters:
$str— the input string to be hashed.$raw_output— optional boolean. Whenfalse(the default),md5()returns a 32-character lowercase hexadecimal string. Whentrue, it returns the raw 16-byte binary hash.
The return value is always the same length for a given mode, no matter how long the input is — a one-character string and a one-megabyte file both produce a 32-character hex digest.
Basic example
Here $string holds some text and md5() returns its hexadecimal digest. The output is the 32-character hex string:
ed076287532e86365e841e92bfc50d8cThe same input always produces the same digest, so MD5 is deterministic — useful for comparing or indexing data, but it also means an attacker can precompute hashes of common values.
Raw binary output
<?php
$hash = md5("Hello World!", true);
echo bin2hex($hash);
?>When $raw_output is true, md5() returns the raw 16-byte binary hash instead of hex. That is half the size of the hex form, which is handy when you store the digest in a BINARY(16) database column. Here we pass it through bin2hex() to print it, so the output is identical to the default mode:
ed076287532e86365e841e92bfc50d8cWhen to use MD5 (and when not to)
MD5 is fast but cryptographically broken — collisions (two different inputs with the same hash) can be produced deliberately. Choose by use case:
- OK: quick non-security checksums, cache keys, deduplicating files, or matching a legacy system that already stores MD5 digests.
- Not OK: password storage and digital signatures. Use
password_hash()for passwords, andhash('sha256', ...)or stronger for integrity that an attacker might attack.
<?php
// Bad — never store passwords like this:
$bad = md5($password);
// Good — purpose-built, salted, slow on purpose:
$good = password_hash($password, PASSWORD_DEFAULT);Warning: Do not use
md5()for password hashing or digital signatures. It is only appropriate for non-security checksums or legacy compatibility.
Related functions
sha1()— produces a longer 160-bit hash; also no longer collision-resistant.crc32()— a fast 32-bit checksum for error detection, not hashing.bin2hex()— converts the raw binary output ofmd5(..., true)into a readable hex string.