Skip to content

How to Validate Password Strength in PHP

  • by
PHP Password Validation Check for Strength

The below quick example validates the password field values posted via a form. First, it checks if both the password fields are not empty. Then, it applies a regex-based condition to validate the passwords.

When the user provides their account password, it is always recommended to validate the input. Password strength validation is very useful to check whether the password is strong. A strong password makes the user’s account secure and helps to prevent account hacking.

This example uses a pattern and it is a regular expression. The PHP preg_match function returns a boolean if the entered password is matched with this pattern.

This password validation returns true if the entered password has at least 1 uppercase, lowercase, number and special character and with a minimum 8-character length.

The following code snippet validates the password using preg_match() function in PHP with Regular Expression, to check whether it is strong and difficult to guess.

  • Password must be at least 8 characters in length.
  • Password must include at least one upper case letter.
  • Password must include at least one number.
  • Password must include at least one special character.
// Given password
$password = 'user-input-pass';

// Validate password strength
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$number    = preg_match('@[0-9]@', $password);
$specialChars = preg_match('@[^\w]@', $password);

if(!$uppercase || !$lowercase || !$number || !$specialChars || strlen($password) < 8) {
    echo 'Password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character.';
}else{
    echo 'Strong password.';
}

Good luck and I hope this article can be useful. See you in the next article…

If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!

Leave a Reply

Your email address will not be published. Required fields are marked *