Search code examples
phpcountstring-length

how to force user to use > or = 8 char. password?


I want to force user to use > or = 8 char. password but can not get it working for some reason, i tried count() and strlen()

if(count($_POST['newpass']) < 8){
        // ERROR
    }

UPDATE (whole php code for the password change):

    if(!empty($_POST['update'])){
    
    if( strlen( trim( $_POST['newpass'] ) ) < 8 ){
        $error = error('Password should be at least 8 characters in length.');
    }
    
    $options = array("cost"=>4);
    $hashPassword = password_hash($_POST['newpass'],PASSWORD_BCRYPT,$options);
    
    $getpass = $odb -> prepare("SELECT `password` FROM `users` WHERE `ID` = :id");
    $getpass -> execute(array(":id" => $_SESSION['ID']));
    $row = $getpass -> fetch(); 

    $saved_password = $row['password'];
    
    if (password_verify($_POST['oldpass'], $saved_password)) {
      $SQLUpdate = $odb -> prepare("UPDATE `users` SET `password` = :password WHERE `username` = :username AND `ID` = :id");
      $SQLUpdate -> execute(array(':password' => $hashPassword,':username' => $_SESSION['username'], ':id' => $_SESSION['ID']));
      $error = success('Password has been successfully changed');
    } else {
      $error = error('Current password is incorrect.');
    }

}

html form (located in MODAL but that does not matter i guess):

<form method="post">
<div class="form-group">
            <label for="recipient-name" class="col-form-label">Current password</label>
            <input class="form-control" style="color:black;" type="password" id="oldpass" name="oldpass" required="">
          </div>
          <div class="form-group">
            <label for="recipient-name" class="col-form-label">New password</label>
            <input class="form-control" style="color:black;" type="password" id="newpass" name="newpass" required="">
          </div>
      </div>
      <div class="form-group">
      <div class="modal-footer">
            <button class="btn btn-primary" name="update" value="change" type="submit">Change</button>
      </div>
      </div>
      </form>

Solution

  • try this:

    if( isset( $_POST['update'])) {
        echo "password entered: " . $_POST['newpass'] . "<br />";
        if(strlen($_POST['newpass']) < 8 ) {
            echo "Yea nah!, password is too short" . "<br />";
        } else {
            echo "Nah yea!, password is long enough" . "<br />";
        }
    }
    

    result 1:

    password entered: sadfsdf Yea nah!, password is too short

    result 2:

    password entered: asdfghjklo Nah yea!, password is long enough