0

so i have a database with phpmyadmin and there is password column there. I want to make a script that can change password and if the current password is the same as the password in the database, the change will succeed. but if the current password doesnt match the password in the database, change password fail.

when i try it i always get wrong password/failed even though the current password is the same as the password in the database. i check it using Postman

this is the output from postmanpostman

this is my database database

and this is my PHP script

<?php

if ($_SERVER['REQUEST_METHOD']=='POST'){

    $id = $_POST['id'];
    $currentpassword = $_POST['currentpassword'];
    $newpassword = $_POST['newpassword'];

    require_once 'connect.php';

    $sql = "SELECT * FROM user_account WHERE id='$id' ";

    $response = mysqli_query($conn, $sql);

    //echo mysqli_num_rows($response);


    if(mysqli_num_rows($response) > 0){

        $row = mysqli_fetch_assoc($response);

        if (password_verify($currentpassword, $row['password']) ){

            $updatepass = "UPDATE user_account SET password='$newpassword' WHERE id='$id' ";

                if(mysqli_query($conn, $updatepass)) {

                    $result["success"] = "1";
                    $result["message"] = "success";

                    echo json_encode($result);
                    mysqli_close($conn);
                }
                else{

                    $result["success"] = "0";
                    $result["message"] = "error!";
                    echo json_encode($result);

                mysqli_close($conn);
                }

        }else{
            $result['success'] = "0";
            $result['message'] = "Wrong password.";
            echo json_encode($result);

            mysqli_close($conn);
        }

    }

}


?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

1 Answers1

1

From the manual

password_verify — Verifies that a password matches a hash

and you store the passwords as raw passwords. You need to store the password in your database as hashed password with password_hash() function so the password_verify function returns true.

//for example replace this
$query = "insert into user_account(name, email, password) values ('testing','testing@gmail.com','1234567')";
//with this
$query = "insert into user_account(name, email, password) values ('testing','testing@gmail.com','" . password_hash('1234567') . "')";
Accountant م
  • 6,975
  • 3
  • 41
  • 61
  • ah so thats the problem, how if i dont want to hash the password? how can i check if the currentpassword is the same with the password in database ? – Nigel Justin Nov 29 '18 at 07:34
  • 1
    Just do normal comparison without password_verify e.g:`if ($currentpassword == $row['password'])` . But **don't** do that , you should hash the passwords, or if your database is stolen, the attacker will get all your clients passwords in *plain text*! – Accountant م Nov 29 '18 at 13:17