Calculate MD5 hash using PHP

Calculate MD5 hash using PHP

MD5 is one of the most commonly used in hashing algorithms, and that’s why PHP language provides several native functions to help developers with calculating MD5 hash easily.

MD5 Hash Algorithm

If you don’t know about MD5, this is the short introduction about it.

The MD5 message-digest algorithm is a widely used hash function producing a 128-bit hash value. Although MD5 was initially designed to be used as a cryptographic hash function, it has been found to suffer from extensive vulnerabilities. It can still be used as a checksum to verify data integrity, but only against unintentional corruption. It remains suitable for other non-cryptographic purposes, for example for determining the partition for a particular key in a partitioned database.Wikipedia

Purpose of using MD5 in PHP applications

There are several common usages for MD5, such as:

  • Storing one-way hashing passwords. Since MD5 hash is almost impossible to crack, so it can be safe to store this hash password in database. However, there are some security issues found with it, hence, make sure to know them before using MD5.
  • Verifying file integrity, or checksum. MD5 is pretty much being used this way. When an original file is created, it will be calculated with an unique MD5 hash value. When the file is distributed across the networks, clients need to make sure that the file is original one and hasn’t been modified yet. So when the original file is distributed, it will come with a MD5 checksum value. Clients will download the file and compare with the given value from distributors. If the value is different, then either the downloaded file is corrupted or the file has been modified.

Calculate MD5 hash in PHP

Up to this point, you might have the idea why MD5 is being used.

Let’s move to the programming part, how to calculate MD5 using PHP.

There are two provided functions to calculate MD5.

  • md5() : to calculate MD5 hash value for a given string.
  • md5_file(): to calculate MD5 hash value for a given file.

Following is the demo code for the usage of those above functions.

$data = "";
echo md5($data); // this output: d456edbf820ac71ee1897b1d9bbe6347

$file = "F:/input.jpg";
echo md5_file($file); // depending on your input file, it will give different results.

On second case, when the file input is the path of the file in your computer, it’s better to use slash / character for  directory separator on Windows, and it’s certainly that one for Linux or MacOS.


In this article, I have shared with you about MD5 and some ideas about it.

Also, the article mentions the usage of how to use native PHP functions to calculate MD5 hash value.

Hope you find it useful for your projects, and have fun!