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

Hàm sha1-file() trong PHP

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

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

The sha1_file() function calculates the sha1 (Secure Hash Algorithm 1) hash of a file.

This function calculates the sha1 hash of the file using the US Secure Hash Algorithm 1, and returns that hash. To calculate the sha1 hash of a string, use the sha1() function.

The following table summarizes the technical details of this function.

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

Syntax

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

sha1_file(filename, raw_format);

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

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

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

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

2ef7bde608ce5404e97d5f042f95f89f1c232871

Tip: The sha1_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 SHA1 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 sha1_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 20. Default value is false which returns the hash as a 40-character hexadecimal number.

More Examples

Here're some more examples showing how sha1_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 SHA1 hash of a file in a text file.

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

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

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

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

// Verifying the current SHA1 hash with previous one
if(sha1_file("post.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