PHP – Password Hash & Password Verify with Example
In this tutorial, we are going to see how to authenticate a user using PDO and password_verify().
First, make sure your passwords are stored in the database using password_hash() function.
If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot authenticate a user if you are not logged in.
Suppose the user’s credentials come from a POST request, try the following code:
Example: Authenticate a user using PDO and password_verify()
<?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 ID!"; } else { echo "Invalid ID!"; } ?>
- In the first line, we create a PDO prepared statement, from a query in which the data is replaced with a question mark (?).
- In the second line, we run the query.
- And the third line, we get a row from a table.
- The next line, we check both if our query returned data, if it did! We check the password.