PHP md5_file()Function
Examples
Calculate the MD5 hash of the text file "test.txt":
$filename = "test.txt";
$md5file = md5_file($filename);
echo $md5file;
?>
The above code will output:
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.
From RFC 1321 - MD5 message-digest algorithm:The MD5 message-digest algorithm takes a message of arbitrary length as input and converts it into a 128-bit "fingerprint" or "message digest" value to represent that input, with the converted value as the result. The MD5 algorithm is primarily designed for digital signature applications; in this digital signature application, a larger file is compressed in a secure manner before being encrypted (where the encryption process is accomplished by setting a private key under a public key in a cryptosystem such as RSA).
To calculate the MD5 hash of a string, use the md5()function.
Syntax
| Parameter | Description |
|---|---|
| file | Required. Specifies the file to be calculated. |
| raw | Optional. A boolean value that specifies hexadecimal or binary output format:
|
Technical Details
| Return value: | Returns the calculated MD5 hash on success, or FALSE on failure. |
|---|---|
| PHP Version: | 4.2.0+ |
| Changelog: | In PHP 5.0,rawthe parameter became optional. As of PHP 5.1, md5_file() can be used with wrappers. For example: md5_file("http://w3cschool.cc/..") |
More Examples
Example 1
Store the MD5 hash of "test.txt" in a file:
$md5file = md5_file("test.txt");
file_put_contents("md5file.txt",$md5file);
?>
Detect whether "test.txt" has been changed (i.e., whether the MD5 hash has been changed):
$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 above code will output:
PHP String Reference Manual Other Extensions