-2

I am trying to build a form with a password input. I am trying to hash the password via php password_hash and save it in the DB. And when the users logs in, i will hash his input and check if its the same like in the DB.

The Problem is that when I use password_hash it gives me a random output everytime I refresh. The input is still the same. That makes it impossible for the user to log in because the outputhash will never match whats in the DB.

I am testing it like that:

$pw = "hello";
echo password_hash ($pw, PASSWORD_DEFAULT);

the first echo = $2y$10$7GwPLFNIhybl6tcyuYsH..Dtgfn2hF7RUDwZ99o7BkL6eza4Dsope;
echo again = $2y$10$7tvaZHupw8Ik8Id/ImHCHekpp/Deg4E.XkG82zaVYx262Exv3zMde;

Am I doing smt wrong? plz help

Gupta
  • 8,882
  • 4
  • 49
  • 59
hatemjapo
  • 800
  • 3
  • 8
  • 30
  • 2
    you use `password_verify` to match... – Andrew Dec 25 '15 at 16:59
  • 1
    and so it should. RTM if you want to keep a constant hash. http://php.net/manual/en/function.password-hash.php – Funk Forty Niner Dec 25 '15 at 17:15
  • Possible duplicate of [Using PHP 5.5's \`password\_hash()\` and verify function, am I doing it right?](http://stackoverflow.com/questions/14992367/using-php-5-5s-password-hash-and-verify-function-am-i-doing-it-right) – JamesQMurphy Dec 25 '15 at 18:03

1 Answers1

2

Yes. you are doing something wrong.

The hash is expected to change on every request. That's the purpose.

What you need to be doing is verfiying the password against that hash.

if(password_verify($password, $hash)){
    //correct
}

Don't try to compare the hash on every page load.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • How can i compare the password with the hash if the hash is changing everytime i load the page? – hatemjapo Dec 25 '15 at 17:23
  • @hatemjapo The `hash` should be stored somewhere `securely`. Such as a database, or a file. For testing purposes, you can store it in `$_SESSION['hash'] = $hash` and then check for it on page load `$hash = isset($_SESSION['hash']) ? $_SESSION['hash'] : false;` Then you can do `if($hash){ if($password_verify($password, $hash){`...etc – Ohgodwhy Dec 25 '15 at 17:24
  • i tried this. I made a form, where i had to type in a pw. I saved it in a DB. Now i tried to match the input with the hash in the database. it looks like this: `$sql = "SELECT * from user WHERE email = '$email'"; $res = mysqli_query($link,$sql); $user = mysqli_fetch_assoc($res); $hash = $user['password']; if(password_verify($password, $hash)) echo 'logged in'; else echo 'not found'; ' – hatemjapo Dec 25 '15 at 17:55