PHP - Hash equals() Function
Definition and Usage
The hash_equals() function compares two given strings at the same time and return true if equal.
Syntax
hash_equals ( string $known_string , string $user_string ) : bool
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
known_string The string which will be compared. |
| 2 |
user_string The string given by user. |
Return Values
PHP hash_equals() function returns a boolean i.e true if the strings are equal and false if not.
PHP Version
This function will work from PHP Version greater than 5.6.0.
Example 1
Working of hash_equals() −
<?php
$known_str = crypt('tutorialspoint','$5$rounds=1000$salttest$');
$usr_str = crypt('tutorialspoint','$5$rounds=1000$salttest$');
$res = hash_equals($known_str, $usr_str);
var_dump($res);
?>
Output
This will produce the following result −
bool(true)
Example 2
Comparing hash using hash_equals −
<?php
$known_str = crypt('tutorialspoint','$5$rounds=1000$salttest$');
$usr_str = crypt('helloworld','$5$rounds=1000$salttest$');
$res = hash_equals($known_str, $usr_str);
var_dump($res);
?>
Output
This will produce the following result −
bool(false)
Example 3
Comparing hash from hash() and hash_file() −
<?php
$hash1 = hash("md5", 'Welcome to Tutorialspoint');
file_put_contents('filetest.txt', 'Welcome to Tutorialspoint');
// create file filetest.txt with content : 'Welcome to Tutorialspoint'
$hash2 = hash_file('md5', 'filetest.txt');
$_compare = hash_equals($hash1, $hash2);
var_dump($_compare);
?>
Output
This will produce the following result −
bool(true)
php_function_reference.htm
Advertisements