Authenticating a user using PDO and password_verify()
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 PDO properly.
First of all make sure that your passwords are stored in the database using password_hash() function.
Assuming we've already got a valid PDO instance in the variable called $pdo, while user's credentials are coming from POST request, here is the code you need:
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$_POST['email']]);
$user = $stmt->fetch();
if ($user && password_verify($_POST['pass'], $user['pass']))
{
echo "valid!";
} else {
echo "invalid";
}
As you can see, some tricks are used to make this code less bloated.
In the first line we are creating a PDO prepared statement, from a query where the actual data is substituted with a question mark - a placeholder.
In the second line we are executing the query, sending the data apart from the query - so it can't do any harm, intentional or non-intentional.
And in the third line we are simply fetching a row from a table.
The next line is a little trick: we are checking both whether our query returned any data at all, and - only in case it did! - verifying the password. Clean, concise and neat.
Related articles:
- SELECT query with PDO
- INSERT query using PDO
- UPDATE query using PDO
- How to connect to MySQL using PDO
- PDO Examples
- How to check if email exists in the database?
- Select the number of rows using PDO
- How to create a WHERE clause for PDO dynamically
- DELETE query using PDO
- How to create a prepared statement for UPDATE query
- Getting a nested array when multiple rows are linked to a single entry
- How to execute 1000s INSERT/UPDATE queries with PDO?
- Adding a field name in the ORDER BY clause based on the user's choice
- INSERT helper function for PDO Mysql
- PDO Examples
- PDO Examples
Comments:
Thanks for writing the BEST (only?) comprehensible intro guide for deciphering the PDO/MySQLi PHP quagmire! You are a hero! Love the way you break down steps instead of "handwaving" through the actual implementation.
You might consider doing an SQL startup guide (you already come close to this) for people trying to figure out exactly where their database "lives" (for example, on a shared server) complete with pre-built code designed for confirming that the connection is working and a working PDO query that the beginner can build out and modify to suit their use case.
Overcoming the "is it my code, or is it even working?" hurdle prevents a lot of people from accessing the myriad benefits of SQL.
Do you take small contract work, by chance?
Amazing! This site is great. I am new to PHP and your content has been invaluable. I have a knack for spotting poor code and I am focused on building secure applications from the start, also a bit obsessed with writing the "most correct" code possible. The tutorials that are out there are atrocious and you're helping me learn PHP without being delusional. The code above is beautiful compared to the monstrosities I've found across the web. Thanks again.
You are doing a great Job.Thanks a lot
I cannot get this to work. var_dump shows the post of the email, password, and username to process.php page. I only get 'invalid' and never 'valid'. db check shows hashed password, but this code doesn't work for me. $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$_POST['email']]); $user = $stmt->fetch(); if ($user && password_verify($_POST['password'], $user['username'])) { echo "valid!"; } else { echo "invalid"; ?> Is there something very obvious that i'm missing. ???
Fetching the stored email and comparing it with the posted email is what I was expecting to see in the tutorial script.
Reply:
Ok, I see where it coming from.
Look, you don't fetch an email to compare. The database doesn't work this way. The comparison is done by the database, when you are running the query. So the comparison is already done and you can fetch only two things: either an array that contains the entered email, or FALSE if it weren't found.
So again, you don't have to fetch to compare emails - it is already done by the database. You are fetching the password hash to compare.
Please I am lost here! Please help me understand this fine tutorial:
Line 1 is searching a database table for an undefined email address. Line 2 is executing using an email from a form, not the one from the database table! Should we not be comparing the form email with the copy in the database table for authentication? Shouldn't Line 1 be accessing the form email address?
Please help
Reply:
Hello Adolf!
Thank you for the very good question! This indeed should have been explained in the article.
What are we doing here is searching for the email from the form. We are effectively running a query that looks like
just doing it in 2 steps:
All in all, the process is very similar to the regular query, we are only doing it in two steps. As we always should, because not a single variable should be added to the query directly, but only through a question mark. This will guarantee us from errors of all sorts, not to mention SQL injection.
Hope it is clear now, but don't hesitate to write back if not!
amazing articles. thank u
Thanks you , very helpfull ;)
Ok, i can help but i am potato with GitHub, i need to learn how to use it first... and right now i'm too busy. But if you want, you can send me something like a Word document or Text file ?
Thank you !
Reply:
Hello Daniel!
Thank you for your comments!
Regarding the translation, I will put the text for the SQL injection article on Github so everyone will be able to fix the grammar there. I'll be grateful if you would help.
Bombolo: ^ That would be very useful for a lot of people.
And yes it would be.
Hello, I love this site, I am just starting using PHP for database operations and I feel I got lucky in stumbling upon this site, because it has the best information.
Related to this article, could you do an article about storing passwords and users data in a secure way?
That would be very useful for a loy of people.