4

I'm trying to store an encrypted password in MySQL and as for the register part it works as it should how ever when i try to do the login things go south.

I can not verify $_POST['password'] against the hash stored in MySQL. I have no idea what I'm doing wrong.

Here is my register.php which works as it should:

register.php (working)

$post_password = mysqli_real_escape_string($_POST['password']);
$password_hash = password_hash($post_password, PASSWORD_BCRYPT);
mysqli_query goes here...

login.php (not working)

$con = mysqli_connect("XXX","XXX","XXX","XXX");
$post_username = mysqli_real_escape_string($con,$_POST['username']);
$post_password = mysqli_real_escape_string($con,$_POST['password']);

// Getting the stored Hash Password from MySQL
$getHash = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM anvandare WHERE username = '$post_username'"));
$got_Hash = $getHash['password'];

// Checking if what the user typed in matches the Hash stored in MySQL
// **This is where it all goes wrong**
if (password_verify($post_password, $got_Hash)) {
echo "The posted password matches the hashed one";
}
else {
echo "The posted password does not match the hashed one";
}

When I run the code above I get the "Correct password" message by just entering the username and leaving the password field out.

What am I missing?

7
  • 1
    Your are not converting the newly entered password at the time of login into hash for comparing, like you did when storing them, Commented Feb 4, 2015 at 10:26
  • did you try mysqli_fetch_array?? plus do convert your password by password_hash() Commented Feb 4, 2015 at 10:28
  • @DennisEnström it happend to every one. Commented Feb 4, 2015 at 10:36
  • @habibulhaq is right it happens to everyone. will write it as a answer. Commented Feb 4, 2015 at 10:57
  • 1
    mysqli_real_escape_string is for making a string safe for inserting into a database. It is not for making a string safe for running through a hashing function. Commented Feb 4, 2015 at 10:58

1 Answer 1

2

Actually you need to make sure that you are allowing more than 100 characters in your password column so that all the hashed password can be saved in the field. This was also happening with me, the script was correct and everything was working fine but the only mistake I was doing was that I didn't allow more than 40 characters in the password field which was the biggest error. After incrementing the maximum limit from 40 to 100, everything is working fine:)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.