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

黄舟
Release: 2023-03-16 22:48:01
Original
1502 people have browsed it

Example

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

<?php
$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;
?>
Copy after login

The above code will output:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
Copy after login

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)
Copy after login
ParametersDescription
file Required. Specifies the file to be calculated.
rawOptional. 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);
?>
Copy after login

检测 "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.";
}
?>
Copy after login

上面的代码将输出:

The file is ok.
Copy after login


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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template