PHP sha1_file()Function
Examples
Calculate the SHA-1 hash of the text file "test.txt":
$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;
?>
The above code will output:
Definition and Usage
The sha1_file() function calculates the SHA-1 hash of a file.
The sha1_file() function uses the US Secure Hash Algorithm 1.
Explanation from RFC 3174 - US Secure Hash Algorithm 1:SHA-1 produces a 160-bit output called a message digest. The message digest can be input to a signature algorithm that generates or verifies a message signature. Signing the message digest rather than the message improves process efficiency because the message digest is usually much smaller than the message. The verifier of a digital signature must use the same hash algorithm as the creator of the digital signature.
Returns the calculated SHA-1 hash on success, or FALSE on failure.
Syntax
| Parameters | Description |
|---|---|
| file | Required. Specifies the file to calculate. |
| raw | Optional. A boolean value that specifies hex or binary output format:
|
Technical Details
| Return value: | Returns the calculated SHA-1 hash on success, or FALSE on failure. |
|---|---|
| PHP Version: | 4.3.0+ |
| Changelog: | In PHP 5.0,rawthe parameter became optional. As of PHP 5.1, sha1_file() can be used with wrappers. For example: sha1_file("http://w3cschool.cc/..") |
More Examples
Example 1
Store the SHA-1 hash of "test.txt" in a file:
$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):
$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:
PHP String Reference Manual Other Extensions