How to Validate Password Strength in PHP
When the user provides their account password, it always recommended validating the input. Password strength validation is very useful to check whether the password is strong. Strong password makes the user’s account secure and helps to prevent account hack.
Using Regex (Regular Expression), you can easily validate the password strength in PHP. In the example code, we will show you how to check password strength and validate a strong password in PHP using Regex.
The following code snippet, validate 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 = 'your password';
if($password){
echo 'Strong password.';
}else{
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.';
}
// Validate password strength function
function validPass($string) {
$containsSmallLetter = preg_match('/[a-z]/', $string);
$containsCapsLetter = preg_match('/[A-Z]/', $string);
$containsDigit = preg_match('/\d/', $string);
$containsSpecial = preg_match('/[^a-zA-Z\d]/', $string);
return ($containsSmallLetter && $containsCapsLetter && $containsDigit && $containsSpecial && strlen($string) < 8);
}
PHP
- asked 5 years ago
- Gul Hafiz