如何使用 php 和 pdo 更新散列密码

How do you update a hashed password with php and pdo

上个月我为一个学校项目做了一个论坛,但我希望用户可以更改自己的密码。如何使用 PHP 和 PDO 更新密码。

我认为你可以使用:

$password = $_POST['password'];
$confirm_password = $_POST['confirm_password']; 

if($password == $confirm_password){
    $stmt = $conn->prepare("UPDATE password SET password = 
    'password_hash($password)' WHERE id=$id");
} else {
     .....
}

但这不是我想要的...

我有一个表格,但我无法显示它,因为出了点问题。 希望大家帮帮我。

您在这里使用的是 cargo cult prepared statement,它无法为您提供免受 SQL 注入的保护。正确的代码是

$stmt = $conn->prepare("UPDATE password SET password = ? WHERE id=?");
$stmt->execute([password_hash($password), $id])

当然,你所做的就是在散列后将新密码写入数据库

$password = $_POST['password'];
$confirm_password = $_POST['confirm_password']; 

if($password == $confirm_password){

    $stmt = $conn->prepare("UPDATE password SET password = :pwd WHERE id=:id");
    $stmt->execute([':pwd' => password_hash($password), ':id'=> $id]);
} else {
     .....
}

Your script was wide open to SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements in either the MYSQLI_ or PDO API's

我找到了我在密码哈希中遗漏 PASSWORD_DEFAULT 的解决方案。 如果我做错了什么留下反应,我将不胜感激。

if(isset($_POST['update_password'])){
$id = $_SESSION['user_id'];  
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password']; 

if(strlen($password) >= 8){
    if($password == $confirm_password){

        $new_password = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("UPDATE forum_inhoud SET password = :new_password 
        WHERE id=:id");
        $stmt->execute([
            ':new_password' => $new_password,
            ':id' => $id
        ]);

        $_SESSION['success'] = 'Wachtwoord is bijgewerkt!';
        header('Location: ../../profile.php');
        exit(0);
    }
} else {
    $_SESSION['failed'] = 'Er is iets misgegaan!';
    header('Location: ../../profile.php');
    exit(0);
}   
}