Simple password validator for PHP

/* 
 * Simple password construct validator for PHP 
 * Joaquim Homrighausen <joho@webbplatsen.se>
 * May 30, 2019 
 * TEAMYUJO 
 * 
 * Do whatever you want with this snippet :) 
 * 
 * This may not necessarily agree with the section
 * "Strength of Memorized Secrets" in the document
 * from NIST:
 *
 * NIST Special Publication 800-63B 
 * Digital Identity Guidelines 
 * Authentication and Lifecycle Management 
 * https://pages.nist.gov/800-63-3/sp800-63b.html 
 */

function password_check_construct ($pstr, $min_length = 8)
{
  //Setup pattern and stuff minimum requested length into it
  if ($min_length < 4) {
    //We need at least four characters to satisfy our regexp
    $min_length = 4;
  }

  $match_rules = '/^(?=.{'.(int)$min_length.',})(?=.*[a-z])(?=.*[0-9])(?=.*[A-Z])(?=.*[[:punct:]]).*$/';

  //Require at least one a-z, one A-z, one 0-9, and one punctuation/special character
  if (preg_match ($match_rules, $pstr) === 1) {
    return (true);
  }
  return (false);
}

This is also available as a gist on GitHub. Knock yourself out 🙂

There’s a similar variant using mb_ereg_match() available here:
Simple password validator for PHP using mb_ereg_match

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.