Changing Password in PHP
Changing the password cannot be done simply in the personal account. The fact is that the user might leave their computer unattended (for example, in the office) while being logged into our website. In this case, if we allowed simply changing the password, a malicious intruder could change the password to another one, which, of course, is very bad.
It is necessary to make it so that changing the password to a new one requires entering the old password.
Let's implement the page changePassword.php.
Upon visiting it, the user will see a form
with two inputs - into the first one they must
enter their old password, and into the second - the new one:
<form action="" method="POST">
<input name="old_password">
<input name="new_password">
<input type="submit" name="submit">
</form>
Upon clicking the submit button, we must do the following:
<?php
$id = $_SESSION['id']; // user id from session
$query = "SELECT * FROM users WHERE id='$id'";
$res = mysqli_query($link, $query);
$user = mysqli_fetch_assoc($res);
$hash = $user['password']; // salted password from DB
$oldPassword = $_POST['old_password'];
$newPassword = $_POST['new_password'];
// Check the correspondence of the hash from the database to the entered old password
if (password_verify($oldPassword, $hash)) {
$newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
$query = "UPDATE users SET password='$newPasswordHash' WHERE id='$id'";
mysqli_query($link, $query);
} else {
// the old password was entered incorrectly, display a message
}
?>
Implement the described password change.