PHP md5_file() Function

In this tutorial, we will learn how we can use the built-in PHP function called md5_file to calculate the MD5 hash value of a given file.

PHP md5_file() Function

Message-Digest Algorithm 5, commonly known as MD5 is a widely used cryptographic hash function that produces a 128-bit hash value.

It takes an input (message) of arbitrary length and produces a fixed-length output (hash) that serves as a digital fingerprint of the message, providing a way to verify data integrity and authenticity.

PHP md5_file() Function

The following shows the syntax of the md5_file() function in PHP.

md5_file(string $filename, bool $binary = false): string|false

The function accepts two main parameters:

  1. filename - this defines the path to the filename whose MD5 hash you wish to calculate.
  2. binary - A Boolean value that determines whether the MD5 digest is returned in raw binary format with a length of 16.

The function will calculate the md5 hash of the specified file and return the value as string output. The md5 has is a 32-character hexadecimal value.

Examples

The following examples demonstrates how to use the md5_file() function in PHP.

Example 1

The following will return the md5 digest value of the .bashrc file.

<?php
$filename = '.bashrc';
if (file_exists($filename)) {
    $hash = md5_file($filename);
    echo "MD5 hash of $filename: $hash";
} else {
    echo "File not found: $filename";
}
?>

The code should calculate the MD5 hash of the provided file and return the value as:

MD5 hash of /home/d3b1an/.bashrc: ee35a240758f374832e809ae0ea4883a

If you make changes to the .bashrc file and calculate the md5 hash file, you should get a different value indicating the file has been modified.

Conclusion

In the tutorial, you learned how to use the PHP md5_file() file to calculate the MD5 digest of an input value allowing you to verify the integrity of a file.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.