Open main menu

How to Check the Strength of Passwords with PHP

There are many ways to check the strength of passwords with PHP, we will use regular expressions because it is really simple.

The following things we are going to validate in the password.

  • An uppercase letter.
  • A lowercase letter.
  • A number.
  • A non-alphanumeric character.
  • Contain at least 6 characters.

If any of the validation fails it will return the error, otherwise it will return true.

function strong_password($password)
{
 $uppercase          = preg_match('@[A-Z]@', $password);
 $lowercase          = preg_match('@[a-z]@', $password);
 $number             = preg_match('@[0-9]@', $password);
 $non_alphanumeric   = preg_match('@[!\@#.$%\?&\*\(\)_\-\+=]@', $password);
    $errors = [];
 
    if(!$uppercase)
    {
        $errors[] = 'The password must contain at least one uppercase character';
    }
 
    if(!$lowercase)
    {
        $errors[] = 'The password must contain at least one lowercase character';
    }
    
    if(!$number)
    {
        $errors[] = 'The password must contain at least one number';
    }
    
    if(!$non_alphanumeric)
    {
        $errors[] = 'The password must contain at least one non-alphanumeric character';
    }
    
    if(strlen($password) < 6)
    {
        $errors[] = 'The password must be at least 6 characters';
    }
 
    return empty($errors) ? TRUE : $errors;
}

With the above simple function, you can check the strength of passwords with PHP, It's is not a complex and is fully functional.