Hướng dẫn
Quảng cáo

Hàm md5-file() trong PHP

Hướng dẫn cách sử dụng hàm md5-file() trong lập trình PHP

Tác dụng của hàm md5-file()

The md5_file() function calculates the MD5 (Message-Digest Algorithm 5) hash of a file.

This function calculates the MD5 hash of the file using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. To calculate the MD5 hash of a string, use the md5() function.

The following table summarizes the technical details of this function.

Return Value: Returns the MD5 hash on success, or FALSE on failure.
Version: PHP 4.2.0+

Syntax

The basic syntax of the md5_file() function is given with:

md5(filename, raw_format);

The following example shows the md5_file() function in action.

<?php
// Sample file
$filename = "hello.txt"; // Contains the text "Hello World!"

// Calculating the hash
echo md5_file($filename);
?>

The output of the above example will look something like this:

ed076287532e86365e841e92bfc50d8c

Tip: The md5_file() function often used to create a unique hash code for a file sent over network. So that after downloading the file user can verify its integrity by calculating its MD5 hash and comparing it against the hash code provided with the distribution. This process makes it possible to ensure that files transferred over a network are not corrupted.


Parameters

The md5_file() function accepts the following parameters.

Parameter Description
string Required. Specifies the name of the file to create the hash from.
raw_format Optional. If set to true, it returns the hash in raw binary format with a length of 16. Default value is false which returns the hash as a 32-character hexadecimal number.

More Examples

Here're some more examples showing how md5_file() function actually works:

The following examples demonstrate how to verify a file for any change using this function.

The PHP code below first stores the MD5 hash of a file in a text file.

<?php
// Sample file
$file = "config.php";

// Storing the MD5 hash of config file in "hash.txt" file
file_put_contents("hash.txt", md5_file($file));
?>

And the following PHP code calculates and compares the MD5 hash of the "config.php" file with its initial MD5 hash stored in the "hash.txt" and tells us whether it is modified or not.

<?php
// Retrieving the stored MD5 hash
$prev_hash = file_get_contents("hash.txt");

// Verifying the current MD5 hash with previous one
if(md5_file("config.php") == $prev_hash){
    echo "There has been no change in the file.";
} else{
    echo "The file has been modified.";
}
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements