如何在PHP中验证密码强度

当用户提供其帐户密码时,它始终建议验证输入。
密码实力验证非常有用,请检查密码是否强。
强密码使用户的帐户安全并有助于防止账户黑客。

使用正则表达式(Regular Expression),我们可以轻松验证PHP中的密码强度。
在示例代码中,我们将展示如何检查密码强度并使用Regex验证PHP中的强密码。

以下代码,使用PHP与正则表达式使用PREG_MATCH()函数验证密码,检查它是否是强大而难以猜测的。

  • 密码长度必须至少为8个字符。
  • 密码必须包含至少一个大写字母。
  • 密码必须包含至少一个数字。
  • 密码必须包含至少一个特殊字符。
//Given password
$password = 'user-input-pass';
//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.';
}
日期:2020-06-02 22:18:58 来源:oir作者:oir