function for checking strlen of a password doesn't work in php

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>

>Solution :

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

Leave a Reply