I just upgraded my PHP installation from version 5.6 to 7.2. I used the count()
function on my login page like so:
if (!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,username,password FROM users WHERE username = :username');
$records->bindParam(':username', $_POST['username']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if (count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
$_SESSION['user_id'] = $results['id'];
header("Location: /");
} else {
$message = 'Sorry, those credentials do not match';
}
endif;
After searching, I found questions and answers similar to this one, but they all were related to WordPress, and I couldn’t find a solution for Pure PHP.
PDO fetch
returns false on failure. So you need to check this case too:
if ($results && count($results) > 0 && password_verify($_POST['password'], $results['password'])) {
$_SESSION['user_id'] = $results['id'];
header("Location: /");
} else {
$message = 'Sorry, those credentials do not match';
}