md5()
The PHP md5() function calculates the MD5 hash of a string. This article covers its syntax, usage, and examples.
The MD5 hash is a widely used cryptographic hash function that produces a 128-bit hash value. The syntax of the md5() function is as follows:
The PHP syntax of the md5()
string md5 ( string $str [, bool $raw_output = false ] )The function takes two parameters, $str and $raw_output. The $str parameter is the string to be hashed, and the $raw_output parameter is a boolean value indicating whether to output the raw binary data of the hash or a hexadecimal string representation of the hash. If the $raw_output parameter is omitted or set to false, the function will output a hexadecimal string representation of the hash.
Example of PHP md5()
<?php
$string = "Hello World!";
$hash = md5($string);
echo $hash;
?>In this example, we have a string variable $string containing some text. We use the md5() function to calculate the MD5 hash of the string.
The output of this code will be:
ed076287532e86365e841e92bfc50d8cAs you can see, the md5() function has calculated the MD5 hash of the string.
Raw Output Example
<?php
$hash = md5("Hello World!", true);
echo bin2hex($hash);
?>When $raw_output is set to true, the function returns the raw 16-byte binary hash. You can use bin2hex() to display it as a hexadecimal string.
Warning: MD5 is cryptographically broken and must not be used for password hashing or digital signatures. Use
password_hash()orhash()with stronger algorithms instead. MD5 is only appropriate for non-security checksums or legacy system compatibility.
The md5() function is a useful tool for working with strings in PHP. By mastering this function, you can become a more proficient PHP developer. We hope this article has been helpful in understanding the md5() function in PHP.
Practice
What is the primary function of the md5() function in PHP?