In this tutorial we will discover how to authenticate a user using PDO and password_verify().
First, make sure your passwords are stored in the database using the password_hash() function.
If you are a “beginner”, you must know how to connect to a MySQL database before using the code below. You can not authenticate a user if you are not logged in.
Suppose the user’s credentials come from a POST request, here’s the code you need:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php $query = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $query->execute([$_POST['email']]); $user = $query->fetch(); if ($user && password_verify($_POST['pass'], $user['pass'])) { echo "Valid identifier!"; } else { echo "Invalid identifier!"; } ?> |
- In the first line, we create a prepared PDO statement, from a query in which the data is replaced with a question mark (?).
- In the second line, we execute the query.
- And in the third line, we get a row from a table.
- The next line we check at once if our query has returned data, and if so! We check the password.