通过使用字符串传入哈希算法名称,我试图使用password_hash()对密码进行哈希:
$password = '121@121';
$hash_method = 'PASSWORD_BCRYPT';
$password_encrypted = password_hash($password, $hash_method);然而,这导致了一个警告:
警告: password_hash()期望参数2是整数,字符串给定
如果我想动态地确定算法(例如从数据库中的配置变量集),如何将字符串值传递给password_hash()
发布于 2019-11-09 09:36:15
之所以发生这种情况,是因为PASSWORD_BCRYPT是一个常量,而不是一个字符串。PASSWORD_BCRYPT是一个对人类友好的数值版本--它节省了记住10亿个数字及其相应值的费用。
编辑信息
Dharman发现了这 --表明从PHP7.4中加密类型的const值将不再是数值。
密码散列算法标识符现在是可空字符串,而不是整数。
PASSWORD_DEFAULT was int 1; now is NULL
PASSWORD_BCRYPT was int 1; now is string '2y'
PASSWORD_ARGON2I was int 2; now is string 'argon2i'
PASSWORD_ARGON2ID was int 3; now is string 'argon2id'只要去掉引号就行了:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
$password = '121@121';
$hash_method = PASSWORD_BCRYPT;
$password_encrypted = password_hash($password, $hash_method);
echo '<pre>'. print_r($password_encrypted, 1) .'</pre>';如果从PASSWORD_BCRYPT或数据库获取constant(),则可以使用constant()函数:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
$password = '121@121';
$hash_method = 'PASSWORD_BCRYPT';
$password_encrypted = password_hash($password, constant($hash_method));
echo '<pre>'. print_r($password_encrypted, 1) .'</pre>';发布于 2019-11-09 09:41:07
您可以使用constant()函数。
password_hash($password, constant($hash_method));constant()接受字符串作为参数,并返回同名常量的值。它应该与defined()一起使用,以确保这样的常量存在,并且不会收到警告。
例如:
$algorithm_value = defined($hash_method) ? constant($hash_method) : PASSWORD_DEFAULT;
$password_encrypted = password_hash($password, $algorithm_value);发布于 2019-11-09 10:14:00
您应该设置第二个参数$algo of password_hash,使用密码算法常数 PASSWORD_BCRYPT,而不是字符串'PASSWORD_BCRYPT'。
/**
* (PHP 5 >= 5.5.0, PHP 5)<br/>
*
* Creates a password hash.
* @link http://www.php.net/manual/en/function.password-hash.php
* @param string $password The user's password.
* @param int $algo A <a href="http://www.php.net/manual/en/password.constants.php" class="link">password algorithm constant</a> denoting the algorithm to use when hashing the password.
* @param array $options [optional] <p> An associative array containing options. See the <a href="http://www.php.net/manual/en/password.constants.php" class="link">password algorithm constants</a> for documentation on the supported options for each algorithm.
* If omitted, a random salt will be created and the default cost will be used.
* <b>Warning<b>
* <p>
* The salt option has been deprecated as of PHP 7.0.0. It is now
* preferred to simply use the salt that is generated by default.
* </p>
* @return string|bool Returns the hashed password, or FALSE on failure.
* @since 5.5.0
*/
function password_hash ($password, $algo, $options = null) {}https://stackoverflow.com/questions/58777942
复制相似问题