Calculate MD5 hash of the File with PHP

  • Avinash
  • 0
  • Jun 30, 2012
  • Web Development

In this article we will see how to calculate the MD5 hash of any file using PHP. We have core function availble in PHP to create a MD5 hash of any file.

Get MD5 Hash of File using PHP

All you need to calculate MD5 hash is just a valid path of the file. Once you have a valid path then you can use below code to get the MD5 hash of the file.

$file_path = "valid file path here"; $md5_hash = md5_file($file_path); echo $md5_hash;
  $file_path = "valid file path here";
 
  $md5_hash = md5_file($file_path);
 
  echo $md5_hash;

This function will return MD5 hash on success and FALSE on error.

What is the use of MD5 Hash?

This was the first question came to my mind when I have seen this function very long ago. But after few mins of finding I got the reason for the same.

Let me explain it from scratch. I hope all of you have seen the PHP Download page (this is not specific to PHP). You will see that PHP team provides the MD5 hash of the file just below the download link. Have a look at below image for the same.

PHP Downloads md5 hash

Reason to provide MD5 hash is that we can verify that downloaded file is same as source file or not.

To verify the file you can use above code and generate the MD5 hash of the downloaded file and compare it with source file md5 hash. If hashes are matched then your files are proper and if not the there must be some data loss or file corrupted during the download.

Conclusion

I hope this article is useful for you and from now on you will verify the MD5 hashes of the files after downloading the files. Please consider sharing this article as SHARING IS CARING.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: