19

I am trying to create a password check script. I already have checks for email (for not allowed characters) like this:

  public function checkEmail($email)
  {
    if (filter_var($email, FILTER_VALIDATE_EMAIL))
      return true;
    else
      return false;   
  }

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.

Brian Willis
  • 22,768
  • 9
  • 46
  • 50
Byakugan
  • 981
  • 4
  • 15
  • 34

1 Answers1

85
public function checkPassword($pwd, &$errors) {
    $errors_init = $errors;

    if (strlen($pwd) < 8) {
        $errors[] = "Password too short!";
    }

    if (!preg_match("#[0-9]+#", $pwd)) {
        $errors[] = "Password must include at least one number!";
    }

    if (!preg_match("#[a-zA-Z]+#", $pwd)) {
        $errors[] = "Password must include at least one letter!";
    }     

    return ($errors == $errors_init);
}

Edited version of this: http://www.cafewebmaster.com/check-password-strength-safety-php-and-regex

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • I think you should have [a-zA-Z] in last, right? And actually Byakugan's definition to last one alphanumeric, but I think he ment 1 alpha, 1 number, strlen>=8 (which you have done here, except that A-z). – raPHPid May 25 '12 at 10:55
  • if there's an error you can return a JSON object, describing the error in code and message, like: return json_encode(array("ok"=>1,"msg"=>"length<8 chars")); –  May 25 '12 at 10:59
  • @Byakugan - Use a second parameter passed by-reference, so the function can put the message there if necessary. That's more robust than using the return value for boolean or for a string (error message). – martinstoeckli May 25 '12 at 11:11
  • Fixed a-zA-Z and added error messages the way martinstoeckli suggested. – Jeroen May 25 '12 at 11:58
  • @Jeroen - Because you don't know, what `$errors` contains when passed to the function, you should initialize it with null. Otherwise it's well done. – martinstoeckli May 25 '12 at 14:02
  • Fixed, but instead of setting it to `null`, I save its initial value and compare it at the end - this way it gets combined with errors from other code if necessary. – Jeroen May 25 '12 at 14:04