Authenticating a user using mysqli and password_verify()
That's extremely popular question on various forums and Stack Overflow. And 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']))
{
// credentials are OK, add user in a session etc...;
} else {
// login failed;
}
Here we are checking in one condition whether a user exists and whether the password is correct.
Note that is is not advised to provide a distinct error message if a user not found. Just 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:
- Mysqli tutorial (how to use it properly)
- How to connect properly using mysqli
- How to report errors in mysqli
- How to check whether a value exists in a database using mysqli prepared statements
- Mysqli helper function
- Why mysqli prepared statemens are so hard to use?
- How to get the number rows that has been actually changed
- Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
- Mysqli examples
- Mysqli's features you probably would like to know about
- How to run INSERT query using Mysqli
- How to use mysqli properly
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote