yii\base\Security::generatePasswordHash PHP Méthode

generatePasswordHash() public méthode

The generated hash can be stored in database. Later when a password needs to be validated, the hash can be fetched and passed to Security::validatePassword. For example, php generates the hash (usually done during user registration or when the password is changed) $hash = Yii::$app->getSecurity()->generatePasswordHash($password); ...save $hash in database... during login, validate if the password entered is correct using $hash fetched from database if (Yii::$app->getSecurity()->validatePassword($password, $hash) { password is good } else { password is bad }
See also: validatePassword()
public generatePasswordHash ( string $password, integer $cost = null ) : string
$password string The password to be hashed.
$cost integer Cost parameter used by the Blowfish hash algorithm. The higher the value of cost, the longer it takes to generate the hash and to verify a password against it. Higher cost therefore slows down a brute-force attack. For best protection against brute-force attacks, set it to the highest value that is tolerable on production servers. The time taken to compute the hash doubles for every increment by one of $cost.
Résultat string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', the output is always 60 ASCII characters, when set to 'password_hash' the output length might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
    public function generatePasswordHash($password, $cost = null)
    {
        if ($cost === null) {
            $cost = $this->passwordHashCost;
        }
        if (function_exists('password_hash')) {
            /** @noinspection PhpUndefinedConstantInspection */
            return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
        }
        $salt = $this->generateSalt($cost);
        $hash = crypt($password, $salt);
        // strlen() is safe since crypt() returns only ascii
        if (!is_string($hash) || strlen($hash) !== 60) {
            throw new Exception('Unknown error occurred while generating hash.');
        }
        return $hash;
    }

Usage Example

 private function createUser($username, $password, $email)
 {
     if ($this->canUpdateRootUser()) {
         $security = new Security();
         $password_hash = $security->generatePasswordHash($password);
         $result = $this->db->createCommand()->update('{{%user}}', ['username' => $username, 'password_hash' => $password_hash, 'email' => $email], ['id' => '1'])->execute();
         if ($result > 0) {
             return true;
         }
     }
     return false;
 }
All Usage Examples Of yii\base\Security::generatePasswordHash