Using the MD5 algorithm in PHP is very easy because it has a native md5() function.
Syntax (>= PHP 4):
md5(string $string, bool $binary = false): string
Basic example:
<?php
$str = "Hello world!";
echo md5($str);
?>
The above example will output:
86fb269d190d2c85f6e0468ceca42a20
Example #2 with parameter $binary
set to TRUE
:
The PHP function also has a second optional parameter $binary
(default value = FALSE
). When this parameter is set to true, the md5 hash string is returned in raw binary format with a length of 16.
<?php
$str = "Hello world!";
echo md5($str, true);
?>
Example #2 will output (unreadable in the browser):
&
,F*
Example #3 with $salt before string to be encrypted:
In some cases, it is worth using a salted MD5 hash for added security. This means that you add the string "salt" before or after the string to be encrypted.
<?php
$salt = "i#8^*uu"; //your arbitrary secret key
$str = "Hello world!";
echo md5($salt . $str, true);
?>
Example #3 will output:
5e5eb686808a7c39710dccf1ce03a4e6