Compute the SHA-1 hash of the text file "test.txt":
<?php$filename = "test.txt";$sha1file = sha1_file($filename);echo $sha1file;?>The above code will output:
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434dThe sha1_file() function calculates the SHA-1 hash of a file.
The sha1_file() function uses the American Secure Hash algorithm1.
Explanation from RFC 3174 - US Secure Hash Algorithm 1: SHA-1 produces a 160-bit output called the message digest. The message digest can be fed into a signature algorithm that generates or verifies the message signature. Signing the message digest instead of the message can improve process efficiency because the size of the message digest is usually much smaller than the message. The verifier of a digital signature must use the same hashing algorithm as the creator of the digital signature.
Returns the computed SHA-1 hash on success, or FALSE on failure.
sha1_file( file,raw )
parameter | describe |
---|---|
file | Required. Specifies the file to be calculated. |
raw | Optional. A Boolean value specifying the hexadecimal or binary output format: TRUE - raw 20-character binary format FALSE - Default. 40 character hexadecimal number |
Return value: | Returns the computed SHA-1 hash on success, or FALSE on failure. |
---|---|
PHP version: | 4.3.0+ |
Update log: | In PHP 5.0, the raw parameter becomes optional. Since PHP 5.1, sha1_file() can be used through encapsulation. For example: sha1_file("http://w3cschool.cc/..") |
Store the SHA-1 hash of "test.txt" in the file:
<?php$sha1file = sha1_file("test.txt");file_put_contents("sha1file.txt",$sha1file);?>Detect whether "test.txt" has been changed (i.e. whether the SHA-1 hash has been changed):
<?php$sha1file = file_get_contents("sha1file.txt");if (sha1_file("test.txt") == $sha1file) { echo "The file is ok."; }else { echo "The file has been changed ."; }?>The above code will output:
The file is ok.