PHP - Hash hmac file() Function
Definition and Usage
The hash_hmac_file() function is used to generate keyed hash value for the given file contents using HMAC method.
HMAC stands for keyed-hash message authentication code or hash-based message authentication code. It makes use of cryptographic hash function like md5, sha-256 and a secret key to hash the file contents given.
Syntax
hash_hmac_file ( string $algo , string $filename , string $key [, bool $raw_output = FALSE ] ) : string
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
algo Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc. To get the full list of algorithms supported, check for hash_hmac_algos() |
| 2 |
filename The filepath to get the file contents. |
| 3 |
key Secret key to generate HMAC variant of the message digest. |
| 4 |
raw_output By default the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data. |
Return Values
The hash_hmac_file() function returns a string of calculated message digest that will in the form of lowercase hexits if raw_output is false otherwise it will return raw binary data.
PHP Version
This function will work from PHP Version greater than 5.1.2.
Example 1
Using hash_hmac_file() −
<?php
file_put_contents('file2.txt', 'Welcome to Tutorialspoint');
echo hash_hmac_file('md5', 'file2.txt', 'anysecretkey');
?>
Output
This will produce the following result −
e519cec21ac0c04a92ff5b358931b49d
Example 2
Difference in hash_hmac_file() output when file contents are changed −
<?php
file_put_contents('abc.txt', 'Hello');
echo hash_hmac_file('sha256', 'abc.txt', 'mysecretkey');
echo "<br/><br/>";
file_put_contents('abc.txt', 'World');
echo hash_hmac_file('md5', 'abc.txt', 'anysecretkey');
?>
Output
This will produce the following result −
362a60a6ef4e35f9559304a6b5372b070c97ba33cb4a747503c9c58b5c85e6db2652fb7ccf4cff91df4f08add44b93b2
Example 3
Difference in hash_file() and hash_hmac_file() output −
<?php
file_put_contents('filetest.txt', 'Welcome to Tutorialspoint');
echo hash_file('sha256', 'filetest.txt');
echo "<br/><br/>";
file_put_contents('abc.txt', 'Welcome to Tutorialspoint');
echo hash_hmac_file('sha256', 'abc.txt', 'mysecretkey');
?>
Output
This will produce the following result −
a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e7f8a726d250c08400820b3a1818f5b650784990eee7f23e3f1946373f2dd6e96