-1

My login system was working fine and then I decided to use password hash. I looked around and can not seem to find my issue. When I register the user, the password is hashed in the database. When I go to login, it is not recognizing the password and saying it is incorrect. Any recommendations of how to fix the issue?

public function evaluate($data) {

      $email = addslashes($data['email']);
      $password = addslashes($data['password']);

      $sql = "SELECT * FROM users WHERE email = '$email' && password = '$password' LIMIT 1";
      $stmt = $this->connect()->prepare($sql);
      $stmt->execute();

      if($row = $stmt->fetch()) {

        if(password_hash($password, $row['password'])) {

          $_SESSION['mfg_userid'] = $row['userid'];

        } else {

          $this->error .= "The email or password you have entered is incorrect. Please try again.";

        }

      } else {

        $this->error .= "The email or password you have entered is incorrect. Please try again.";

      }

      return $this->error;

    }
justRyan
  • 7
  • 3
  • 1
    You can't use the hashed password in your query. You need to select by email only and then verify the password with `password_verify` – Andrea Olivato Jul 20 '21 at 04:26
  • 4
    Does this answer your question? [How to use PHP's password\_hash to hash and verify passwords](https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords) – Andrea Olivato Jul 20 '21 at 04:26
  • 2
    Furthermore your code is open to SQL Injection, please use prepared statements via `bind_param` instead of adding parameters to your code. Read [here](https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords) – Andrea Olivato Jul 20 '21 at 04:27

1 Answers1

0

In PHP the password_hash() function generates a hashed string which can be verified with the help of password_verify() function. So, In your case you need to use password_verify() instead of password_hash() in your if condition.

$hash = password_hash('asdf@123', PASSWORD_DEFAULT);
if (password_verify('asdf@123', $hash)) {
    echo 'Password is valid!'; //correct output
} else {
    echo 'Invalid password.';
}