Site icon Bytefreaks.net

PHP: Functions that check passwords if they are strong enough

Advertisements

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 Latin letter, a caps Latin letter, a number and a special character.

//Function that checks if string has at least one small Latin letter, one caps Latin letter, a number and a special character
function validString($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);
}

In case you do not want to check for the case of the Latin characters and you just want to see if there is any of them we can merge the two checks as follows

//Function that checks if string has at least one Latin letter, a number and a special character
function validString($string) {
  $containsLetter = preg_match('/[a-zA-Z]/', $string);
  $containsDigit = preg_match('/\d/', $string);
  $containsSpecial = preg_match('/[^a-zA-Z\d]/', $string);
  return ($containsLetter && $containsDigit && $containsSpecial);
}

This post is also available in: Greek

Exit mobile version