简体   繁体   English

使用密码散列更新当前密码

[英]Updating current passwords with password hashing

I'm trying to run password_hash on current password values in my database...我正在尝试对数据库中的当前password值运行password_hash ...

$mysqli->query("UPDATE users SET password = '" . password_hash('password', PASSWORD_DEFAULT) . "');

I'm getting no error, but the password does not work after the update as expected.我没有收到任何错误,但密码在更新后无法正常工作。 The only thing I can think of is the above query is not getting the current password value from the table.我唯一能想到的是上面的查询没有从表中获取当前密码值。

No need for prepared statements as I'm just mucking about locally for this one.不需要准备好的声明,因为我只是在本地为这个做准备。

You can't mix PHP and SQL like this.你不能像这样混合 PHP 和 SQL。 password_hash is a PHP function. You need to fetch the user data into PHP, iterate over it and save each record into the database. password_hash是一个 PHP function。你需要将用户数据取到 PHP 中,迭代它并将每条记录保存到数据库中。 Use SQL transactions when doing so.这样做时使用 SQL 笔交易。

// Remember to always enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset

$users = $mysqli->query('SELECT Id, password FROM users');

// start transaction and prepare a statement
$mysqli->begin_transaction();
$stmt = $mysqli->prepare('UPDATE users SET `password`=? WHERE Id=?');

foreach ($users as $user) {
    // make a hash out of the password
    $hash = password_hash($user['password'], PASSWORD_DEFAULT);
    $stmt->bind_param('ss', $hash, $user['Id']);
    $stmt->execute();
}

// commit the data to DB and end transaction
$mysqli->commit();

Always use prepared statements.始终使用准备好的语句。 There's absolutely no excuse not to use parameter binding.绝对没有理由不使用参数绑定。 If you were to use parameter binding from the start you would have noticed much quicker that your approach is flawed.如果您从一开始就使用参数绑定,您会更快地注意到您的方法存在缺陷。 Now you have changed all passwords to the string password ;现在您已将所有密码更改为字符串password every account has the same password.每个帐户都有相同的密码。

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

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