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
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