PHP sha1_file() 函數
實例
計算文本文件"test.txt" 的SHA-1 散列:
<?php
$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;
?>
$filename = "test.txt";
$sha1file = sha1_file($filename);
echo $sha1file;
?>
上面的代碼將輸出:
aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
定義和用法
sha1_file() 函數計算文件的SHA-1 散列。
sha1_file() 函數使用美國Secure Hash 算法1。
來自RFC 3174的解釋-美國Secure Hash算法1:SHA-1產生一個名為報文摘要的160位的輸出。報文摘要可以被輸入到一個可生成或驗證報文簽名的簽名算法。對報文摘要進行簽名,而不是對報文進行簽名,這樣可以提高進程效率,因為報文摘要的大小通常比報文要小很多。數字簽名的驗證者必須像數字簽名的創建者一樣,使用相同的散列算法。
如果成功則返回已計算的SHA-1 散列,如果失敗則返回FALSE。
語法
sha1_file( file,raw )
参数 | 描述 |
---|---|
file | 必需。规定要计算的文件。 |
raw | 可选。一个规定十六进制或二进制输出格式的布尔值:
|
技術細節
返回值: | 如果成功則返回已計算的SHA-1 散列,如果失敗則返回FALSE。 |
---|---|
PHP 版本: | 4.3.0+ |
更新日誌: | 在PHP 5.0中, raw參數變成可選的。 自PHP 5.1 起,可以通過封裝使用sha1_file()。 例如: sha1_file("http://w3cschool.cc/..") |
更多實例
實例1
在文件中存儲"test.txt" 的SHA-1 散列:
<?php
$sha1file = sha1_file("test.txt");
file_put_contents("sha1file.txt",$sha1file);
?>
$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.";
}
?>
$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 String參考手冊