1

So I have a login page which worked fine without hashed passwords but of course, that wasn't secure so I decided to hash the passwords when registering. but I don't know how and where should I use verify_password when I'm selecting the password from the database.
I use while to see if there is a result with the username and password entered like this:

$q = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$x = $conn->query($q);
if ($x->num_rows > 0) {
    while ($row = $x->fetch_assoc()) {
        //Logged in seccesfully!
    }
} else {
    // Username or password is wrong!
}
  • Please read up on [SQL Injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Adder Mar 19 '19 at 11:45
  • well firstly you should be using [prepared statements and parameterised queries](http://php.net/manual/en/mysqli.prepare.php) to protect yourself from [SQL Injection attacks](http://bobby-tables.com/). Otherwise your security is still hopeless. Then, what you'd need to do is select the user details from the database (so select just by username, removing the password clause from the WHERE), and then compare the (hashed) password which comes from the database to the password the user entered, by providing both values to the password_verify() function. – ADyson Mar 19 '19 at 11:47

1 Answers1

0

password_hash() function can simplify our lives and our code can be secure. When you need to hash a password, just feed it to the function and it will return the hash which you can store in your database.

$hash = password_hash($password, PASSWORD_DEFAULT);

Now that you have seen how to generate hashes with the new API, let’s see how to verify a password. Remember that you store the hashes in a database, but it’s the plain password that you get when a user logs in. The password_verify() function takes a plain password and the hashed string as its two arguments. It returns true if the hash matches the specified password.

<?php
if (password_verify($password, $hash)) {
    // Success!
}
else {
    // Invalid credentials
}

for more info read

Shanteshwar Inde
  • 1,438
  • 4
  • 17
  • 27