Home / Using hash algorithms in PHP

Using hash algorithms in PHP

PHP has a number of hashing algorithms available for creating hash values of files and strings. A hash is a non-reversible fixed length string which has a number of applications, such as storing a password in a database in a way that can not be read (in this example when someone logs in the hash is applied to their submitted plain text password and compared with the hashed value in the database). This post looks at how to show the available hashes in PHP and how to use the hash() function to generate a hash value.

To get the list of all the available hash algorithms in PHP use the hash_algos() function, for example:

print_r(hash_algos());

This will give you a zero based index array containing all the hash algorithms available. The output from the command above is shown below:

Array
(
    [0] => md4
    [1] => md5
    [2] => sha1
    [3] => sha256
    [4] => sha384
    [5] => sha512
    [6] => ripemd128
    [7] => ripemd160
    [8] => whirlpool
    [9] => tiger128,3
    [10] => tiger160,3
    [11] => tiger192,3
    [12] => tiger128,4
    [13] => tiger160,4
    [14] => tiger192,4
    [15] => snefru
    [16] => gost
    [17] => adler32
    [18] => crc32
    [19] => crc32b
    [20] => haval128,3
    [21] => haval160,3
    [22] => haval192,3
    [23] => haval224,3
    [24] => haval256,3
    [25] => haval128,4
    [26] => haval160,4
    [27] => haval192,4
    [28] => haval224,4
    [29] => haval256,4
    [30] => haval128,5
    [31] => haval160,5
    [32] => haval192,5
    [33] => haval224,5
    [34] => haval256,5
)

As you can see there are a lot. The most commonly used ones are MD5 and SHA1 and these have their own functions as well as the generic hash and hash_file functions.

To calculate the hash on a string using md5, for example, you can do this:

echo hash("md5", "this is my string to be hashed");
OR
echo md5("this is my string to be hashed");

Both of the above examples will output the same hash which is as follows:

85e77eff2c856f43b7a9f59b7171d666

Picking one of the other hash algorithms at random, we could use e.g. haval256,3 like so:

echo hash("haval256,3", "this is my string to be hashed");
// outputs 2e5b5a9abc71b4ef8f24bba766b0de18e7799380349909cc34f74570b45fce76

You can also create a hash of a file using the hash_file, md5_file and sha1_file functions, e.g.:

$hash = hash_file("md5", "/path/to/file");
$hash = md5_file("/path/to/file");
$hash = sha1_file("/path/to/file");