簡體   English   中英

CakePHP 3 - 比較密碼

[英]CakePHP 3 - Compare passwords

我有兩個字段“密碼”(這個字段在數據庫中)和 confirm_password(這個字段不在數據庫中)

好吧,我需要比較 password == confirm_password ..但我不知道為“confirm_password”創建自定義驗證...需要在數據庫中包含此字段嗎?

我該怎么做?

通常,您可以通過$context參數訪問自定義驗證規則中的所有數據,該參數存儲在data密鑰中,即$context['data']['confirm_password'] ,然后可以將其與當前字段值進行比較。

$validator->add('password', 'passwordsEqual', [
    'rule' => function ($value, $context) {
        return
            isset($context['data']['confirm_password']) &&
            $context['data']['confirm_password'] === $value;
    }
]);

話雖如此,最近引入了一個完全做到這一點的compareWith驗證規則。

https://github.com/cakephp/cakephp/pull/5813

$validator->add('password', [
    'compare' => [
        'rule' => ['compareWith', 'confirm_password']
    ]
]);

現在在驗證器類中有一個方法調用sameAs,用於版本3.2或更高版本。

 $validator -> sameAs('password_match','password','Passwords not equal.');

API

我知道這是遲到的答案,但會幫助其他人。

// Your password hash value (get from database )
$hash = '$2y$10$MC84b2abTpj3TgHbpcTh2OYW5sb2j7YHg.Rj/DWiUBKYRJ5./NaRi';
$plain_text = '123456'; // get from form and do not make hash. just use what user entred.
  
if (password_verify($plain_text, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

或者

$hasher = new DefaultPasswordHasher();
$check = $hasher->check($plain_text,$hash); // it will return true/false

暫無
暫無

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

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