PHP - hash_file() 函式



定義和用法

hash_file() 函式將返回給定檔案內容的雜湊值。返回值將是一個小寫十六進位制字串。

語法

hash_file ( string $algo , string $filename [, bool $raw_output = FALSE ] ) : string

引數

序號 引數及描述
1

algo

雜湊演算法的名稱。hash 提供了大量的演算法,一些重要的演算法包括 md5、sha256 等。

要獲取支援的完整演算法列表,請使用雜湊函式 hash_algos()

2

filename

檔案路徑,其內容將被轉換為雜湊值。

3

raw_output

預設值為 false,因此它返回小寫十六進位制值。如果值為 true,它將返回原始二進位制資料。

返回值

如果 raw_output 為 false,PHP hash_file() 函式返回一個小寫十六進位制字串;否則,它將返回原始二進位制資料。

PHP 版本

此函式適用於 PHP 5.1.2 以上版本。

示例 1

生成給定檔案內容的雜湊值:

<?php
   file_put_contents('filetest.txt', 'Welcome to Tutorialspoint'); 
   // create file filetest.txt with content : 'Welcome to Tutorialspoint'
   echo hash_file('md5', 'filetest.txt');
?>

輸出

這將產生以下結果:

8ab923b97822bd258bf882e41de6ebff

示例 2

測試相同內容的 hash() 和 hash_file():

<?php
   echo hash("md5", 'Welcome to Tutorialspoint');
   echo "<br/>";
   file_put_contents('filetest.txt', 'Welcome to Tutorialspoint'); 
   // create file filetest.txt with content : 'Welcome to Tutorialspoint'
   echo hash_file('md5', 'filetest.txt');
?>

輸出

這將產生以下結果:

8ab923b97822bd258bf882e41de6ebff<br/>8ab923b97822bd258bf882e41de6ebff

示例 3

對影像使用 hash_file():

<?php
   echo hash_file('md5', 'https://tutorialspoint.tw/images/tp-logo-diamond.png')
?>

輸出

這將產生以下結果:

0bdba90368971801a0d5c7e81679cdc9
php_function_reference.htm
廣告