PHP Function Reference

PHP sha1_file() Function



The PHP sha1_file() function calculates the SHA-1 (Secure Hash Algorithm 1) hash of the file specified by filename using the US Secure Hash Algorithm 1.

From RFC 3174: SHA-1 produces a condensed representation of a message or a data file. When a message of length less than 264 bits is input, the SHA-1 produces a 160-bit output called a message digest. The message digest can then, for example, be input to a signature algorithm which generates or verifies the signature for the message. Signing the message digest rather than the message often improves the efficiency of the process because the message digest is usually much smaller in size than the message. The same hash algorithm must be used by the verifier of a digital signature as was used by the creator of the digital signature. Any change to the message in transit will, with very high probability, result in a different message digest, and the signature will fail to verify.

Syntax

sha1_file(filename, binary)

Parameters

filename Required. Specify the filename of the file to hash.
binary Optional. If set to true, then the SHA-1 digest is returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number. Default is false.

Return Value

Returns a string on success, false otherwise.

Example:

The example below illustrates on sha1_file() function.

<?php
$fname = "test.txt";

echo "The filename is: $fname \n";
echo "The hash of filename is: \n";
echo sha1_file($fname);
?>

The output of the above code will be:

The filename is: test.txt 
The hash of filename is: 
cfac94bc1730c351c2929932992b46a26225407f

Example:

Consider one more example where optional parameter is used to calculate the hash of the file in different formats.

<?php
$fname = "test.txt";

echo "20 character binary format:\n";
echo sha1_file($fname, true);
echo "\n40 character hexadecimal number: \n";
echo sha1_file($fname);
?>

The output of the above code will be:

20 character binary format:
Ϭ”¼0ÃQ’™2™+F¢b%@
40 character hexadecimal number: 
cfac94bc1730c351c2929932992b46a26225407f

❮ PHP String Reference