function md5()

Using MD5 algorithm in PHP

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:

$str = "Hello world!";
echo md5($str);

The above example will output:


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.

$str = "Hello world!";
echo md5($str, true);

Example #2 will output (unreadable in the browser):


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.

$salt = "i#8^*uu"; //your arbitrary secret key
$str = "Hello world!";
echo md5($salt . $str, true);

Example #3 will output:


External resources about MD5 in PHP: w3resource