简体   繁体   English

使用yii将密码存储为哈希

[英]Store password as hash using yii

How can I store password as hash? 如何将密码存储为哈希?

<?php

class StudentRegisterForm extends CActiveRecord {

public $email;
public $password;
public $studentName;
public $academicYear;
public $moduleName;
private $_identity;

/**
 * Declares the validation rules.
 * The rules state that username and password are required,
 * and password needs to be authenticated.
 */
public static function model($className = __CLASS__) {
    return parent::model($className);
}

public function tableName() {
    return '{{students}}';
}

public function rules() {
    return array(
        // username and password are required
        array('email, password,studentName,academicYear,moduleName', 'required'),
    );
}

/**
 * Declares attribute labels.
 */
public function attributeLabels() {
    return array(
        'id' => 'Id',
        'email' => 'Email',
        'password' => 'Password',
        'studentName' => 'Student Name',
        'academicYear' => 'Acadamic Year',
        'moduleName' => 'Module Name',
    );
}

    /**
 * Checks if the given password is correct.
 * @param string the password to be validated
 * @return boolean whether the password is valid
 */
public function validatePassword($password) {
    return CPasswordHelper::verifyPassword($password, $this->password);
}

/**
 * Generates the password hash.
 * @param string password
 * @return string hash
 */
public function hashPassword($password) {
    return CPasswordHelper::hashPassword($password);
}

//     * This is invoked before the record is saved.
//     * @return boolean whether the record should be saved.
public function beforeSave() 
{
    if (parent::beforeSave()) {

        return true;
    }
    else
        return false;
}

//     * This is invoked after the record is saved.

public function afterSave() {
    parent::afterSave();
}
}

You can directly use this function for creating a hash password in yii2 您可以直接使用此功能在yii2中创建哈希密码

 $password = Yii::$app->security>generatePasswordHash($password_string);

and for validating the password use 并用于验证密码使用

Yii::$app->getSecurity()->validatePassword($password_string,  $password)

call this below function : 调用以下函数:

public function hashPassword($password) {
    return CPasswordHelper::hashPassword($password);
}

in before save method , then you can store the password in hash. 在保存方法之前,您可以将密码存储在哈希中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM