Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading