Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check password strength

Short answer

Check the length and the presence of the required characters:

<?php
 
function passwordErrors(string $password): array
{
    $errors = [];
 
    if (mb_strlen($password) < 8) {
        $errors[] = 'at least 8 characters';
    }
 
    if (!preg_match('/\p{L}/u', $password)) {
        $errors[] = 'a letter';
    }
 
    if (!preg_match('/\d/', $password)) {
        $errors[] = 'a digit';
    }
 
    return $errors;
}
 
echo json_encode(passwordErrors('abc')), "\n";
echo json_encode(passwordErrors('correct horse 42'));

Output:

["at least 8 characters","a digit"]
[]

Length matters more than complexity

A long phrase is stronger than a short password with symbols. Do not cap the length too tightly or forbid spaces — and the password must still be stored only as password_hash().

Functions used in this recipe

  • preg_match — Tests a string against a regular expression.
  • mb_strlen — Returns the number of characters in a string.
  • password_hash — Creates a password hash for storing in a database.

Thanks for reading!

Donate to the site — we work hard for you.