Friday, April 19, 2013

Check password strength / safety with PHP and Regex

<?php
function checkPasswordLength($password, &$message) {
    if(strlen($password) < 8) {
        $message = "Password too short!";
        return false;
    }
    if(strlen($password) > 20) {
        $message = "Password too long!";
        return false;
    }
    if( !preg_match("#[0-9]+#", $password) ) {
        $message = "Password must include at least one number!";
        return false;
    }
    if( !preg_match("#[a-z]+#", $password) ) {
        $message = "Password must include at least one letter!";
        return false;
    }
    if( !preg_match("#[A-Z]+#", $password) ) {
        $message = "Password must include at least one CAPS!";
        return false;
    }
    if( !preg_match("#\W+#", $password) ) {
        $message = "Password must include at least one symbol!";
        return false;
    }
    return true;
}
?>

No comments:

Post a Comment