Authenticating a user using mysqli and password_verify()

  1. Comments

That's extremely popular question on various forums and Stack Overflow. An at the same time it's a very good example that can show you how to use Mysqli properly.

First of all make sure that your passwords are stored in the database using password_hash() function.

Then, given $conn variable contains a valid mysqli instance (here you can see how to connect with mysqli properly), the code to check the password will be as simple as that:

$stmt $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s"$_POST['email']);
$stmt->execute();
$user $stmt->get_result()->fetch_assoc();

if (
$user && password_verify($_POST['pass'], $user['pass']))
{
    echo 
"valid!";
} else {
    echo 
"invalid";
}

Note that is is not advised to provide a distinct error message if a user not found. Gust a generic "Credentials are not correct" would be enough. Otherwise it will help a malicious user to find whether a certain email is registered on the site.


Related articles: