0
  • I'm creating an PHP update password page the the new and the confirm new password are working but.
  • I wanted to check that the current password is correct before moving on to password update.
  • I'm using an encrypt in my database.
  • The new pass & confirm pass are both working I just wanted to check if the current session password is correct and give an error if it's wrong I'm not having any errors but whatever I put in the current_password input it will always return me "Wrong password! (Palavra-Passe incorreta!)"

Here is my code:

<?php
// Inicializar a sessão
session_start();

// Verificar se o utilizador está ligado, se não estiver, redireccioná-lo para a página de início de sessão
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

if (isset($_SESSION['id']) && isset($_SESSION['password'])) {
    # code...
}


// Incluir ficheiro de configuração
require_once "config.php";

// Definir variáveis e inicializar com valores vazios
$current_password = $new_password = $confirm_password = "";
$current_password_err = $new_password_err = $confirm_password_err = "";

// Processamento de dados do formulário quando o formulário é submetido
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validar Palavra-Passe
    if (empty(trim($_POST["current_password"]))) {
        $current_password_err = "Este campo é obrigatório!";
    } else {
        $current_password = trim($_POST["current_password"]);
    }

    // Validar Nova Palavra-Passe
    if (empty(trim($_POST["new_password"]))) {
        $new_password_err = "Este campo é obrigatório!";
    } elseif (strlen(trim($_POST["new_password"])) < 6) {
        $new_password_err = "A Palavra-Passe deve ter pelo menos 6 caracteres.";
    } else {
        $new_password = trim($_POST["new_password"]);
    }

    // Validar Confirmação de Palavra-Passe
    if (empty(trim($_POST["confirm_password"]))) {
        $confirm_password_err = "Este campo é obrigatório!";
    } else {
        $confirm_password = trim($_POST["confirm_password"]);
        if (empty($new_password_err) && ($new_password != $confirm_password)) {
            $confirm_password_err = "A Palavra-Passe não correspondeu.";
        }
    }

    // Validar as credenciais
    if (empty($current_password_err) && empty($new_password_err) && empty($confirm_password_err)) {

        $id = $_SESSION['id'];
        $sql = "SELECT password FROM users WHERE id = '$id' AND password = '$current_password'";

        $result = mysqli_query($conn, $sql);
        if (mysqli_num_rows($result) === 1) {
            // Palavra-Passe está correta, atualizar Palavra-Passe
            $sql_2 = "UPDATE users SET password = '$new_password' WHERE id = '$id'";
            mysqli_query($conn, $sql_2);
            session_destroy();
            header("location: login.php");

            // Alertar utilizador com uma mensagem
            $register_message = "A sua palavra-passe foi atualizada com sucesso!";
            $_SESSION['register_message'] = '<div class="alert alert-success">' . $register_message . '</div>';
            exit();
        } else {
            $current_password_err = "Palavra-Passe incorreta!";
        }
    }

    // Ligação fechada
    mysqli_close($conn);
}
?>
  • 3
    You check the old password the same way you check the password when they're logging in. – Barmar Apr 02 '22 at 01:13
  • I tried using the same code but it's not working... I'll share the login code with you. https://pastebin.com/3acZiCAq – rrenildopereiraa Apr 02 '22 at 23:42
  • i forgot to mention here is what i tried (https://pastebin.com/anNT2ZG9) from what u said about checking the password the same way i do in the login page mb u could help me with `"Fatal error: Uncaught ArgumentCountError: The number of variables must match the number of parameters in the prepared statement in C:\xampp\htdocs\rrpapfct\update-password.php:55 Stack trace: #0 C:\xampp\htdocs\rrpapfct\update-password.php(55): mysqli_stmt_bind_param(Object(mysqli_stmt), 's', NULL) #1 {main} thrown in C:\xampp\htdocs\rrpapfct\update-password.php on line 55"` – rrenildopereiraa Apr 02 '22 at 23:49
  • `UPDATE users SET password = ? WHERE id = ?` has 2 `?` but you only bind one variable `$param_password`. You left out the variable for `id = ?` – Barmar Apr 03 '22 at 02:01
  • I don't see anything in that code that checks the password, it just updates it without checking. And then it tries to do `mysqli_stmt_bind_result($stmt, $password, $hashed_password);` when it's not a `SELECT` query. – Barmar Apr 03 '22 at 02:02
  • So what do I need is only a SELECT query? I would be grateful if you could give me an example of how I can implement this check in code. – rrenildopereiraa Apr 03 '22 at 10:49
  • Hi! I tried what you told me about the SELECT query (https://pastebin.com/YPG6PDvE) but it keeps saying the password is incorrect. I get not errors :/ – rrenildopereiraa Apr 03 '22 at 14:08
  • Since you hash the passwords, you have to use `password_verify()`, just like when validating a login. – Barmar Apr 04 '22 at 02:36

0 Answers0