Search code examples
phppassword-protectionpassword-encryption

password_verify return false from database but true from site?


I need a bit of help here. I don't really understands why these aren't both returning "true". My test user with the id 6 has "test" as password. The value was stored when i created him.

I'm aware that the two hashed values aren't the same, but it seems like everyone is able to do it like that here on stackoverflow :)

<?php

require_once 'includes/database.php';
require_once 'includes/connection.php';

$sql_1 = 'SELECT * FROM anew_users WHERE user_id = 6';
$result_1 = $conn->query($sql_1);
while($row = $result_1->fetch_assoc()) {

    $password = $row["user_password"];

}

$submittedPassword = "test";

echo $password . "<br>";
echo $submittedPassword . "<br>";

$verify = password_verify($submittedPassword, $password);
echo var_dump($verify);

$password = hashPassword('test');
$submittedPassword = "test";

echo $password . "<br>";
echo $submittedPassword . "<br>";

$verify = password_verify($submittedPassword, $password);
echo var_dump($verify);

The output is:

//OUTPUT
$2y$10$aAHYMEvpW2o9ZRsD0XN2XOpYz.dmuqj5v4UdAPIZX9Eo0SW0NjGRe
test
bool(false)

$2y$10$.srmofPee5SWV6nmOy0PAOIlzoJPT0SBnzNN0QkYZKlpk3LzgI7F.
test
bool(true)

I created the password with this code:

function hashPassword($string) {
    $output = password_hash($string, PASSWORD_DEFAULT, ['cost' => 10]);
    return $output;
}

$user_password = escape($_POST["user_password"]);
$user_passwordhashed = hashPassword($user_password);

Thanks in advance.

UPDATE WITH ESCAPE FUNCTION

function escape($string) {
    $string = trim($string);
    $string = stripslashes($string);
    $string = htmlspecialchars($string);
    return $string;     
}

Solution

  • The password that was hashed and stored in the database was not test, but was an empty string.

    $string = '';
    $pass = '$2y$10$aAHYMEvpW2o9ZRsD0XN2XOpYz.dmuqj5v4UdAPIZX9Eo0SW0NjGRe';
    
    $output = password_verify($string, $pass);
    var_dump($output);