PHP - Hash file() Function
Definition and Usage
The hash_file() function will return hash of given file contents. The return value will be a string of lowercase hexits.
Syntax
hash_file ( string $algo , string $filename [, 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, use the hashing function hash_algos() |
| 2 |
filename The file path, the contents of which are to be converted to hash. |
| 3 |
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
PHP hash_file() function returns a string 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
To generate hash of given file contents −
<?php
file_put_contents('filetest.txt', 'Welcome to Tutorialspoint');
// create file filetest.txt with content : 'Welcome to Tutorialspoint'
echo hash_file('md5', 'filetest.txt');
?>
Output
This will produce the following result −
8ab923b97822bd258bf882e41de6ebff
Example 2
Testing hash() and hash_file() for same content −
<?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');
?>
Output
This will produce the following result −
8ab923b97822bd258bf882e41de6ebff<br/>8ab923b97822bd258bf882e41de6ebff
Example 3
Using hash_file() for image −
<?php
echo hash_file('md5', 'https://www.tutorialspoint.com/images/tp-logo-diamond.png')
?>
Output
This will produce the following result −
0bdba90368971801a0d5c7e81679cdc9