PHP | hash_equals() Function

PHP hash_equals() Function


Hello dear readers! welcome back to another edition of our tutorial on PHP. In this tutorial guide, we are going to be discussing about the PHP hash_equals() Function.

The built-in PHP hash_equals() function compares two strings at the same time and returns true if equal.

Syntax

Following below is the syntax to use this function -

hash_equals ( string $known_string , string $user_string ) : bool


Parameter Details

Sr.NoParameter & Description
1

known_string

The string which will be compared.

2

user_string

The string given by user.


Return Value

This built-in PHP function returns true if the strings are equal and false if not.

PHP Version

This built-in function works from PHP version greater than 5.6.0.

Example1

The following below is an example which demonstrates the usage of the hash_equals() function -

<?php
   $known_str = crypt('webdesigntutorialz','$5$rounds=1000$salttest$');
   $usr_str   = crypt('webdesigntutorialz','$5$rounds=1000$salttest$');
   $res = hash_equals($known_str, $usr_str); 
   var_dump($res);
?>

Output

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

bool(true)

Example2

Comparing hash using the PHP hash_equals() function -

<?php
   $known_str = crypt('webdesigntutorialz','$5$rounds=1000$salttest$');
   $usr_str   = crypt('helloworld','$5$rounds=1000$salttest$');
   $res = hash_equals($known_str, $usr_str); 
   var_dump($res);
?>

Output

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

bool(false)

Example3
Comparing hash from hash() and hash_file() -

<?php
   $hash1 = hash("md5", 'Welcome to Webdesigntutorialz');
   file_put_contents('filetest.txt', 'Welcome to Webdesigntutorialz'); 
   // create file filetest.txt with content : 'Welcome to Webdesigntutorialz'
   $hash2 = hash_file('md5', 'filetest.txt');
   $_compare = hash_equals($hash1, $hash2); 
   var_dump($_compare);
?>

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

bool(false)


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial, we will discuss about the hash_file() Function in PHP.

Do feel free to ask your questions where necessary and i 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.