I was making a sign-up page and everything worked and got send to the db but you could enter a weak pwd. I wanted to make sure that the pwd length had a minimum length of 8. I added these lines of code but when I tested it it skipped this code and you could enter any pwd you want. does anyone know why this line is getting skipped and what a sollution for this problem is?
function pwdTooShort($pwd) {
$result;
if (strlen($pwd) > 7) {
$result = true;
}
else{
$result = false;
}
return $result;
}
if (isset($_POST["submit"])) {
$pwd = $_POST["pwd"];
require_once 'functions.inc.php';
if(pwdTooShort($pwd) !== false) {
header("location: ../sign-in.php?error=passwordtooshort");
exit();
}
}
if (isset($_GET["error"])){
if($_GET["error"] == "passwordtooshort"){
echo "<p> password is too short </p>";
}
}
<form action="include/signup.inc.php" method = "post">
<input type="password" name = "pwd" />
</form>
CodePudding user response:
You have some logic issues.
Your pwdTooShort()
will now return true
if the password has more than 7 characters (backwards). You can change that function to:
function pwdTooShort($pwd)
{
// Return true if it is 7 characters or shorter
return mb_strlen($pwd) <= 7;
}
I also changed strlen()
to mb_strlen()
to account for multibyte characters, as @vee suggested in comments.
Improvement suggestion
The if
-statement is technically correct, but is "over complicated".
You can change
if (pwdTooShort($pwd) !== false)
to either
if (pwdTooShort($pwd) === true)
or just
if (pwdTooShort($pwd))
to make it easier to read
CodePudding user response:
From your function name to check password too short, I think it should return true
if too short and false
if it is not.
Here is the code. It is just flip true
and false
.
/**
* Check if password is too short (less than 8 characters).
*
* @param string $pwd The raw password without hash.
* @return bool Return `true` if it is too short, return `false` if it is not.
*/
function pwdTooShort($pwd) {
$result;
if (mb_strlen($pwd) > 7) {
$result = false;
}
else{
$result = true;
}
return $result;
}
The code above, I changed from strlen()
to mb_strlen()
to let it supported multi byte characters (unicode text) and exactly count the characters.
I recommend you not limit the characters to non unicode. This is recommeded by OWASP.
Allow usage of all characters including unicode and whitespace. There should be no password composition rules limiting the type of characters permitted.
The whitespace they said means between character. You can still trim($password)
.
The rest of the code will be work fine with this.