HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMajor

Password checker in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpcheckerpassword

Problem

I have written a password checker using PHP, consisting of many if else statements. Is there any possible way to shorten this code?

function passtest($pass) {
            if (!empty($pass)) { //check if string is empty
                if (ctype_alnum($pass)) { //check if string is alphanumeric
                    if (7 Password passed";
                                }
                                else {
                                    return "No capital letter";
                                }
                            }
                            else {
                                return "No small letter";
                            }
                        }
                        else {
                            return "No number";
                        }
                    }
                    else {
                        return "Password is short";
                    }
                }
                else {
                    return "Password has special character";
                }
            }
            else {
                return "Password field is empty";
            }
        }

Solution

I have an answer which also changes the logic of your code but I think there is a good reason why you should consider it:

function passtest($pass) {
    $errors = array();
    if (empty($pass)) $errors[] = 'Password field is empty';
    if (ctype_alnum($pass)) $errors[] = 'Password has special character';
    [...]

    return '' . implode('', $errors);
}


Since it appears like this is somehow shown to the user I would notifyabout all the errors that happened in choosing the password, so that they can all be corrected in a single try.

Another sidenote: Since your code reminds me of the time where I was just getting started and this seems to be at least somewhat related:
Don't save passwords, save their hashes. And use a good hashing implementation. If you're using PHP >= 5.5, there is a really easy way.

And thanks to "Fge", I can also give you a slightly less easy way for earlier PHP versions (>= 5.3.7).

Code Snippets

function passtest($pass) {
    $errors = array();
    if (empty($pass)) $errors[] = 'Password field is empty';
    if (ctype_alnum($pass)) $errors[] = 'Password has special character';
    [...]

    return '<br />' . implode('<br>', $errors);
}

Context

StackExchange Code Review Q#42095, answer score: 20

Revisions (0)

No revisions yet.