Authenticating a user using PDO and password_verify()

  1. Comments (12)

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: