How to Validate Password Strength in PHP

350

I am trying to create a password check script. So I am looking for a password validation function that checks passwords have at least one alphanumeric character, and one numeric character, and a minimum of 8 characters, and also provides error messages.

Any one suggest me 

Thanks

  • PHP

  • asked 2 months ago
  • Gul Hafiz

2Answer


0

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 string';

// 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.';
}

 

  • answered 2 months ago
  • Community  wiki

0

Following you will find a function that checks a string if it matches certain limitations that are usually applied on passwords.

Specifically, in the following code we check that the input contains at least one small letter, a caps letter, a number and a special character.

//Function that checks if string has at least 8 characters in length and one small letter, one caps letter, a number and a special character
 
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);
    }

 

  • answered 2 months ago
  • Community  wiki

0
  • answered 49 years ago
  • Komal sharma

0
  • answered 49 years ago
  • Packers movers

Your Answer

    Facebook Share