Home >Backend Development >PHP Tutorial >PHP calculates the SHA-1 hash function sha1_file() of a file

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

黄舟
黄舟Original
2017-11-03 09:07:431512browse

Example

Calculate 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:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

Definition and usage

sha1_file() FunctionCalculate the SHA-1 hash of a file.

The sha1_file() function uses the American Secure Hash algorithm 1.

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 calculated SHA-1 hash on success, or FALSE on failure.

Syntax

sha1_file(file,raw)
Parameters Description
file Required. Specifies the file to be calculated.
raw Optional. A Boolean value that specifies the hexadecimal or binary output format:
  • TRUE - raw 20-character binary format

  • FALSE - default. 40 character hexadecimal number

Technical details

Return value : Returns the calculated SHA-1 hash if successful, or FALSE if failed.
PHP Version: 4.3.0+
Change 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/..")

更多实例

实例 1

在文件中存储 "test.txt" 的 SHA-1 散列:

<?php
$sha1file = sha1_file("test.txt");
file_put_contents("sha1file.txt",$sha1file);
?>

检测 "test.txt" 是否已被更改(即 SHA-1 散列是否已被更改):

<?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 file is ok.


The above is the detailed content of PHP calculates the SHA-1 hash function sha1_file() of a file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn