目录

PHP sha1_file() 函数

❮ PHP 字符串参考

示例

计算文本文件 "test.txt" 的 SHA-1 哈希值:

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

上面代码的输出将是:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d


定义和用法

sha1_file() 函数计算文件的 SHA-1 哈希值。

sha1_file() 函数使用美国安全哈希算法 1。

来自 RFC 3174 - 美国安全哈希算法 1:"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."

该函数在成功时返回计算出的 SHA-1 哈希值,在失败时返回 FALSE。


语法

sha1_file( file,raw)

参数值

Parameter Description
file Required. The file to be calculated
raw Optional. A boolean value that specifies hex or binary output format:
  • TRUE - Raw 20 character binary format
  • FALSE - Default. 40 character hex number


技术细节

返回值: 成功时返回计算出的 SHA-1 哈希值,失败时返回 FALSE
PHP 版本: 4.3.0+
变更日志: 从 PHP 5.1 开始,可以将 sha1_file() 与包装器一起使用,例如sha1_文件("https://91xjr.com/..")

更多示例

示例

将 "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.


❮ PHP 字符串参考