PHP

Validate Password Strength

admin by @admin ADMIN
29m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Score a password 0–4 (NIST-inspired, not the full zxcvbn algorithm). Encourages length over complexity; flags well-known weak patterns. Use as a UI hint, not a hard barrier.
PHP
Raw
<?php
function scorePassword(string $pw): array {
    if ($pw === '') return [0, 'Empty'];
    $len = strlen($pw);
    $score = 0;
    if ($len >= 8)  $score++;
    if ($len >= 12) $score++;
    if ($len >= 16) $score++;
    if (preg_match('/[A-Z]/', $pw) && preg_match('/[a-z]/', $pw) && preg_match('/\d/', $pw)) $score++;
    if (preg_match('/[^A-Za-z0-9]/', $pw)) $score++;

    static $blocklist = ['password','12345678','qwerty','letmein','welcome','admin','iloveyou'];
    if (in_array(strtolower($pw), $blocklist, true)) return [0, 'Common password — pick another'];

    $score = min($score, 4);
    $label = ['Very weak','Weak','OK','Strong','Very strong'][$score];
    return [$score, $label];
}

print_r(scorePassword('hunter2'));          // [0, "Very weak"]
print_r(scorePassword('Tr0ub4dor&3'));      // [3, "Strong"]
print_r(scorePassword('correct horse battery staple')); // [4, "Very strong"]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.