PHP Tutorial - PHP sha1_file() Function


The sha1_file() function calculates the SHA-1 hash of a file.


PHP sha1_file() Function has the following syntax.



ParameterIs RequiredDescription
fileRequired.The file to be calculated
rawOptional.A boolean value that specifies hex or binary output format:

Possible values for raw.

  • TRUE - Raw 20 character binary format
  • FALSE - Default. 40 character hex number


PHP sha1_file() Function Returns the calculated SHA-1 hash on success, or FALSE on failure

Example 1

Calculate the SHA-1 hash of the text file "test.txt":

$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;

Example 2

Store the SHA-1 hash of "test.txt" in a file and test if "test.txt" has been changed (that is if the SHA-1 hash has been changed):

<?php//from   w  w w  .ja  va 2s  .  c om
$sha1file = sha1_file("test.txt");

$sha1file = file_get_contents("sha1file.txt");
if (sha1_file("test.txt") == $sha1file){
  echo "The file is ok.";
  echo "The file has been changed.";