簡體   English   中英

function 用於檢查密碼的 strlen 在 php 中不起作用

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

我正在制作一個注冊頁面,一切正常並發送到數據庫,但你可以輸入一個弱密碼。 我想確保密碼長度的最小長度為 8。我添加了這些代碼行,但是當我測試它時,它跳過了這段代碼,你可以輸入任何你想要的密碼。 有誰知道為什么這條線被跳過以及這個問題的解決方案是什么?

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>

你有一些邏輯問題。

如果密碼超過 7 個字符(向后),您的pwdTooShort()現在將返回true 您可以將 function 更改為:

function pwdTooShort($pwd)
{
    // Return true if it is 7 characters or shorter
    return mb_strlen($pwd) <= 7;
}

正如@vee 在評論中建議的那樣,我還將strlen()更改為mb_strlen()以考慮多字節字符。

改進建議

if語句在技術上是正確的,但“過於復雜”。

你可以改變

if (pwdTooShort($pwd) !== false)

要么

if (pwdTooShort($pwd) === true)

要不就

if (pwdTooShort($pwd))

為了更容易閱讀

從您的 function 名稱檢查密碼太短,我認為如果太短它應該返回true ,否則返回false
這是代碼。 它只是翻轉truefalse

/**
 * 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;
}

上面的代碼,我從strlen()更改為mb_strlen()以使其支持多字節字符(unicode 文本)並精確計算字符。
我建議您不要將字符限制為非 unicode。 這是OWASP推薦的。

允許使用所有字符,包括 unicode 和空格。 不應有密碼組合規則限制允許的字符類型。

他們說的空格是字符之間的意思。 您仍然可以trim($password)

代碼的 rest 可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM