2015-12-19 118 views
1

如何將密碼存儲爲散列?使用yii存儲密碼爲散列

<?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(); 
} 
} 

回答

0

調用此函數如下:

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

在之前保存的方法,那麼你可以將密碼哈希存儲。

1

您可以直接在yii2

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

和驗證密碼使用此功能來創建一個哈希密碼使用

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