PHP | hash_file() Function

PHP hash_file() Function


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP hash_file() Function.

The built-in PHP hash_file() function returns hash of the given file contents. The return value will be a string of lowercase hexits.

Syntax

Following below is the syntax to use this function -

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


Parameter Details

Sr.NoParameter & 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 Value

This built-in PHP function returns a string of lowercase hexits if the raw_output is false, otherwise it returns raw binary data.

PHP Version

This PHP function works from PHP version greater than 5.1.2.

Example1

To generate hash of a given file contents -

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

Output

When the above code is executed, it will produce the following result -

98c299a76c4b81497677fc5aa861166d

Example2

Testing hash() and hash_file() for some contents -

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

Output

When the above code is executed, it will produce the following result -

98c299a76c4b81497677fc5aa861166d<br/>98c299a76c4b81497677fc5aa861166d

Example3

Using hash_file() for image -

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

Output

When the above code is executed, it will produce the following result -

0bdba90368971801a0d5c7e81679cdc9


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about the PHP hash_final() Function.

Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Do follow us on our various social media handles available and also subscribe to our newsletter to get our tutorial posts delivered directly to your emails.

Thanks for reading and bye for now.