Seynal Seynal - 4 months ago 23
MySQL Question

PHP call of undefined function hash_equals()

any one can help me out of this problem?
i'm getting error of '

call of undefined function hash_equals()
'
here is my code:

$username = 'Admin';
$password = 'sample1Pasword';

$dbh = new PDO('mysql:host=localhost;dbname=test', $USER, $PASSWORD);

$sth = $dbh->prepare('
SELECT
hash
FROM users
WHERE
username = :username
LIMIT 1
');

$sth->bindParam(':username', $username);

$sth->execute();

$user = $sth->fetch(PDO::FETCH_OBJ);

// Hashing the password with its hash as the salt returns the same hash
if ( hash_equals($user->hash, crypt($password, $user->hash)) ) {
// Ok!
}else{
//user not found
}


I dont know what's going on, i just search for this function but it givin me a problem instead.
sorry for my bad english. Thank you!

Answer

In php.net docs we can find a replacement function for older php versions :

if(!function_exists('hash_equals'))
{
    function hash_equals($str1, $str2)
    {
        if(strlen($str1) != strlen($str2))
        {
            return false;
        }
        else
        {
            $res = $str1 ^ $str2;
            $ret = 0;
            for($i = strlen($res) - 1; $i >= 0; $i--)
            {
                $ret |= ord($res[$i]);
            }
            return !$ret;
        }
    }
}

Otherwise, you could use this library : https://github.com/ircmaxell/password_compat