PHP Tutorial - PHP md5_file() Function






Definition

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

To calculate the MD5 hash of a string, use the md5() function.

Syntax

PHP md5_file() Function has the following syntax.

md5_file(file,raw)

Parameter

ParameterIs RequiredDescription
fileRequired.The file to be calculated
rawOptional.A boolean value that specifies hex or binary output format:

Possible values for raw:

  • TRUE - Raw 16 character binary format
  • FALSE - Default. 32 character hex number




Return

Returns the calculated MD5 hash on success, or FALSE on failure.

Example 1

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


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

The code above generates the following result.

Example 2

Store the MD5 hash of "test.txt" in a file and Test if "test.txt" has been changed.


<?php//  w  w  w .  j av  a 2 s. co m
$md5file = md5_file("test.txt");
file_put_contents("md5file.txt",$md5file);

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

?>

The code above generates the following result.