PHP sha1_file() function
Example
Calculate the SHA-1 hash of the text file "test.txt":
<?php $filename = "test.txt"; $sha1file = sha1_file($filename); echo $sha1file; ?>
Output of the above code:
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
Definition and Usage
The sha1_file() function calculates the SHA-1 hash of the file.
The sha1_file() function uses the United States Secure Hash Algorithm 1.
Explanation from RFC 3174 - The United States Secure Hash Algorithm 1: SHA-1 produces a 160-bit output named a message digest. The message digest can be input into a signature algorithm that can generate or verify a message signature. Signing the message digest instead of the message itself can improve process efficiency, as the size of the message digest is typically much smaller than that of the message. The verifier of the digital signature must use the same hashing algorithm as the creator of the digital signature.
Returns the calculated SHA-1 hash if successful, or FALSE if failed.
Syntax
sha1_file(file,raw)
Parameter | Description |
---|---|
file | Required. Specifies the file to be calculated. |
raw |
Optional. Boolean value, specifies the hexadecimal or binary output format:
|
Technical Details
Return Value: | Returns the calculated SHA-1 hash if successful, or FALSE if failed. |
PHP Version: | 4.3.0+ |
Update Log: |
In PHP 5.0,raw Parameters become optional. Since PHP 5.1, sha1_file() can be used through encapsulation. For example: sha1_file("http://codew3c.com/..") |
More Examples
Example 1
Store the SHA-1 hash of "test.txt" in the file:
<?php $sha1file = sha1_file("test.txt"); file_put_contents("sha1file.txt",$sha1file); ?>
Test if "test.txt" has been modified (i.e., SHA-1 has been modified):
<?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."; } ?>
Output of the above code:
The file is ok.