Home  >  Article  >  Backend Development  >  PHP calculates the MD5 hash function md5_file() of a file

PHP calculates the MD5 hash function md5_file() of a file

黄舟
黄舟Original
2017-11-02 13:26:581790browse

Example

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

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

The above code will output:

d41d8cd98f00b204e9800998ecf8427e

Definition and usage

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

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

Explanation from RFC 1321 - MD5 message digest algorithm: The MD5 message digest algorithm takes information of any length as an input value and converts it into a 128-bit length "fingerprint information" or "message" Summary" value to represent this input value, and the converted value as the result. The MD5 algorithm is primarily designed for digital signature applications where larger files are encrypted using a public key in a cryptographic system such as RSA. (done by setting a private key) before compressing in a secure manner.

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

Syntax

md5_file(file,raw)

Parameters Description

##file Required. Specifies the file to be calculated. ​

raw ​ Optional. A Boolean value specifying the hexadecimal or binary output format:

                TRUE - raw 16-character binary format  

                    FALSE -  default. 32 characters Sixteen -in -made numbers

3 3 3

This returns: If successful, return the calculated MD5 scale, if it fails, it will Return FALSE.

##PHP Version: 4.2.0+

##Change Log: In PHP 5.0 , the raw parameter becomes optional.

                  Since PHP 5.1, md5_file() can be used through encapsulation. For example: md5_file("http://w3cschool.cc/..")

More examples

Instance 1

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

<?php
$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):

<?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.";
}
?>

The above code will output :

The file is ok.

The above is the detailed content of PHP calculates the MD5 hash function md5_file() of a file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn