PHP sha1_file() 函数

定义和用法

sha1_file() 函数计算文件的 SHA-1 散列。

sha1() 函数使用美国 Secure Hash 算法 1。

如果成功,则返回所计算的 SHA-1 散列,如果失败,则返回 false。

语法

sha1_file(file,raw)
参数 描述
string 必需。规定要计算的文件。
charlist

可选。规定十六进制或二进制输出格式:

  • TRUE - 原始 20 字符二进制格式
  • FALSE - 默认。40 字符十六进制数

注释:该参数是 PHP 5.0 中添加的。

例子

例子 1

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

输出:

aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

例子 2

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

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

在本例中,我们将测试 "test.txt" 是否已更改(即 SHA-1 hash 是否已更改):

<?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.