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.
In this case, a simple fix is to change line 302 to: if (is_countable($tombstones) && count($tombstones) > 0) : is_countable() has been introduced in PHP 7.3 exactly for this purpose.
We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array. If we do not set the value for a variable, it returns 0.
The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.
The is_countable() function checks whether the contents of a variable is a countable value or not. This function returns true (1) if the variable is countable, otherwise it returns false/nothing.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With