PHP md5() Function
Topic: PHP String ReferencePrev|Next
Description
The md5()
function calculates the MD5 (Message Digest Algorithm 5) hash of a string.
This function calculates the MD5 hash of string using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. To calculate the MD5 hash of a file, use the md5_file() function.
The following table summarizes the technical details of this function.
Return Value: | Returns the MD5 hash on success, or FALSE on failure. |
---|---|
Version: | PHP 4+ |
Warning: Using the md5()
function to secure passwords is not recommended, due to the fast nature of this hashing algorithm. Use the password_hash()
function to hash passwords.
Syntax
The basic syntax of the md5()
function is given with:
The following example shows the md5()
function in action.
Example
Run this code »<?php
// Sample string
$str = "Sparrow";
// Calculating the hash
echo md5($str);
?>
Parameters
The md5()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the input string. |
raw_format | Optional. If set to true , it returns the hash in raw binary format with a length of 16. Default value is false which returns the hash as a 32-character hexadecimal number. |
More Examples
Here're some more examples showing how md5()
function actually works:
The following example calculates the MD5 hash in different formats.
Example
Run this code »<?php
// Sample string
$str = "Sparrow";
// Calculating the hash
echo "MD5 hash as a 32-character hexadecimal number: ".md5($str)."<br>";
echo "MD5 hash in 16-character raw binary format: ".md5($str, TRUE);
?>
The following example checks whether the two MD5 hashes are identical or not.
Example
Run this code »<?php
// Sample string
$str = "Sparrow";
// Test if two hashes are Identical
if(md5($str) === "ef5a30521df4c0dc7568844eefe7e7e3"){
echo "Sparrows are very social and they live in flocks.";
}
?>