PHP Function Reference

PHP md5_file() Function



The PHP md5_file() function calculates the MD5 hash of the file specified by filename using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

From RFC 1321: The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. The MD5 algorithm is intended for digital signature applications, where a large file must be "compressed" in a secure manner before being encrypted with a private (secret) key under a public-key cryptosystem such as RSA.

Syntax

md5_file(filename, binary)

Parameters

filename Required. Specify the filename of the file to hash.
binary Optional. If set to true, then the MD5 digest is returned in raw binary format with a length of 16, otherwise the returned value is a 32-character hexadecimal number. Default is false.

Return Value

Returns a string on success, false otherwise.

Example:

The example below illustrates on md5_file() function.

<?php
$fname = "test.txt";

echo "The filename is: $fname \n";
echo "The hash of filename is: \n";
echo md5_file($fname);
?>

The output of the above code will be:

The filename is: test.txt 
The hash of filename is: 
49c3b20a3357213b707b93af0daa498d

Example:

Consider one more example where optional parameter is used to calculate the hash of the file in different formats.

<?php
$fname = "test.txt";

echo "16 character binary format:\n";
echo md5_file($fname, true);
echo "\n32 character hexadecimal number: \n";
echo md5_file($fname);
?>

The output of the above code will be:

16 character binary format:
Iò
3W!;p{“¯
ªI
32 character hexadecimal number: 
49c3b20a3357213b707b93af0daa498d

❮ PHP String Reference