写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 源码/ 密码强度校验与提示
安全相关 通用 PHP 7.4+

密码强度校验与提示

长度、字符种类、常见弱密码、连续字符检测,返回具体的不合格原因,而不是只给一个红叉。

完整代码

PHP
<?php
function password_strength(string $pwd): array
{
    $score = 0;
    $tips = [];

    $len = mb_strlen($pwd, 'UTF-8');
    if ($len < 8) {
        $tips[] = '至少 8 个字符';
    } elseif ($len >= 12) {
        $score += 2;
    } else {
        $score += 1;
    }

    $kinds = 0;
    if (preg_match('/[a-z]/', $pwd)) $kinds++;
    if (preg_match('/[A-Z]/', $pwd)) $kinds++;
    if (preg_match('/\d/', $pwd)) $kinds++;
    if (preg_match('/[^a-zA-Z\d]/', $pwd)) $kinds++;
    $score += $kinds;

    if ($kinds < 2) {
        $tips[] = '至少包含字母和数字两类字符';
    }

    $weak = ['12345678', 'password', 'qwerty123', 'abc123456', '11111111', 'admin123'];
    if (in_array(strtolower($pwd), $weak, true)) {
        return [0, ['这是常见弱密码,换一个']];
    }

    if (preg_match('/(.)\1{3,}/u', $pwd)) {
        $tips[] = '不要连续重复同一个字符';
        $score--;
    }
    if (preg_match('/(0123|1234|2345|3456|4567|5678|6789|abcd)/i', $pwd)) {
        $tips[] = '不要使用连续序列';
        $score--;
    }

    $score = max(0, min(5, $score));
    $label = ['很弱', '弱', '一般', '较强', '强', '很强'][$score];
    return [$score, $tips ?: [$label]];
}

怎么用

  1. 注册和改密时调用,$score < 2 拒绝提交,否则把提示显示出来。
  2. 前端可以做实时提示,但服务端必须再校验一次。
  3. 提示要具体,「密码太简单」这种话对用户没有帮助。

注意

  • 不要强制「必须含特殊字符」,长密码更有效,NIST 也不推荐复杂的组合规则。
  • 不要限制特殊字符的种类,用户用中文或 emoji 也应该允许。
  • 真正的防线是 bcrypt 哈希 + 登录限流,强度校验只是第一层。

相关源码