user3326060 user3326060 - 2 months ago 18
PHP Question

PHP Password checker

I have written a password checker using PHP and It worked fine. It consists of many "if else". Is there any way to minimize my usage of "if else" in my code?

function passtest($pass) {
if (!empty($pass)) { //check if string is empty
if (ctype_alnum($pass)) { //check if string is alphanumeric
if (7 < strlen($pass)){ //check if string meets 8 or more characters
if (strcspn($pass, '0123456789') != strlen($pass)){ //check if string has numbers
if (strcspn($pass, 'abcdefghijklmnopqrstuvwxyz') != strlen($pass)) { //check if string has small letters
if (strcspn($pass, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') != strlen($pass)) { //check if string has capital letters
return "<br />Password passed";
}
else {
return "<br />No capital letter";
}
}
else {
return "<br />No small letter";
}
}
else {
return "<br />No number";
}
}
else {
return "<br />Password is short";
}
}
else {
return "<br />Password has special character";
}
}
else {
return "<br />Password field is empty";
}
}

Answer

xkcd
> xkcd

Your function should just test to see if a password was entered. Other than that, it is not your place to tell people what they can and can't use for a password. How long would it take for a hacker to realise my password is Pokémon, for example? That special character is a HUGE entropy booster.

That aside, to actually answer your question, try formulating your statements in the negative:

if( empty($pass)) return "<br />Password field is empty";
if( !ctype_alnum($pass)) return "<br />Password has special character":
// ...

This has the handy side-effect of keeping the error messages next to the condition they represent.

Comments