PHP md5_file() function

Example

Calculate the MD5 hash of the text file "test.txt":

<?php
$filename = "test.txt";
$md5file = md5_file($filename);
echo $md5file;
?>

Output of the above code:

d41d8cd98f00b204e9800998ecf8427e

Definition and Usage

The md5_file() function calculates the MD5 hash of a file.

The md5_file() function uses RSA data security, including the MD5 message digest algorithm.

Explanations from RFC 1321 - MD5 Message Digest Algorithm: The MD5 Message Digest Algorithm takes any length of information as input and converts it into a 128-bit length "fingerprint information" or "message digest" value to represent the input value, and uses the converted value as the result. The MD5 algorithm is mainly designed for digital signature applications; in these digital signature applications, larger files will be compressed in a secure manner before encryption (the encryption process here is completed by setting the private key under a public key in a cryptographic system [such as: RSA]).

If you need to calculate the MD5 hash of a string, please use md5() Function.

Syntax

md5_file(file,raw)
Parameters Description
file Required. Specifies the file to be calculated.
raw

Optional. Boolean value, specifies the hexadecimal or binary output format:

  • TRUE - Original 16-character binary format
  • FALSE - Default. 32-character hexadecimal number

Technical Details

Return Value: Returns the calculated MD5 hash if successful, or FALSE if failed.
PHP Version: 4.2.0+
Update Log:

In PHP 5.0, a new raw Parameters.

Since PHP 5.1, md5_file() can be used by encapsulation. For example: md5_file("http://w3cschool.com.cn/..")

More Examples

Example 1

Store the MD5 hash of "test.txt" in the file:

<?php
$md5file = md5_file("test.txt");
file_put_contents("md5file.txt",$md5file);
?>

Check if "test.txt" has been changed (i.e., the MD5 hash has been changed):

<?php
$md5file = file_get_contents("md5file.txt");
if (md5_file("test.txt") == $md5file)
  {
  echo "The file is ok.";
  }
else
  {
  echo "The file has been changed.";
  }
?>

Output of the above code:

The file is ok.