Check password strength / safety with PHP and Regex

Submitted by n8coder on Wed, 05/13/2009 - 15:51

Password Validation with PHP and Regular Expressions What is a good password? Your birthday, favorite star or first school, car, ...? None of them, because all similar passwords are very easy to crack. My golden rule for safe-passwords is simple: Google or any search engine should NOT find any result for your password-string. But do not search for your password without changing some characters, because it will be visible as clear-text to all networks between your pc and Google server. Another rule: make it hard for password-crackers: Use long passwords with letters, CAPS, numbers and sybols. Let check a password strength with PHP. This is a simple and long example for php beginners.

<?php

$pwd = $_POST['pwd'];

if( strlen($pwd) < 8 ) {
$error .= "Password too short!
";
}

if( strlen($pwd) > 20 ) {
$error .= "Password too long!
";
}

if( strlen($pwd) < 8 ) {
$error .= "Password too short!
";
}

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

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

if( !preg_match("#[A-Z]+#", $pwd) ) {
$error .= "Password must include at least one CAPS!
";
}

if( !preg_match("#\W+#", $pwd) ) {
$error .= "Password must include at least one symbol!
";
}

if($error){
echo "Password validation failure(your choise is weak): $error";
} else {
echo "Your password is strong.";
}

Short example with Regex: And this is the short version of that pwd-check with regexp (lookahead / lookbehind / lookaround) using PHP's PCRE engine.

<?php
$pwd = $_POST['pwd'];

if (preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).*$#", $pwd)){
    echo "Your password is strong.";
} else {
    echo "Your password is not safe.";
}

You can use "\d" instead of "[a-z]" and "\W" instead of non-word characters, symbols. You can make a manual list of most used sybols like [#.-_,$%&!]. Numbers, letters, CAPS: Remember most users dont like passwords with symbols(because of keyboard differences), you can exclude symbol-check. Just check length, letters, caps and numbers.

<?php
$pwd = $_POST['pwd'];

if (preg_match("#.*^(?=.{8,20})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$#", $pwd)){
    echo "Your password is good.";
} else {
    echo "Your password is bad.";
}

Sometimes it is better to do it with javascript before visitor send form.

Submitted by Anonymous (not verified) on Thu, 05/21/2009 - 15:40

Permalink

here is a small list of bad selections

1967
porsche
milan
manchesterunited
newyork
obama
stanford
lessy
01011980
esprit
levis501
adidaspuma

For good passwords make sentences and save the first letter of them. And keep the first half on a paper.

Add new comment