Categories: Bootstrap 3MySqlPHP

Change User Password by Validating Current Password in PHP MySQL

Introduction

In my last tutorial we have seen how we can develop Login and Register feature along with account verification, now in this tutorial I am going focus on how we can provide change password option for the user from there profile.

Changing password is an essential for every software you can take any example from the live applications they all have change password option for there users so that user can easily change there login password.

I am going to move forward my previous tutorial  User Account activation by email verification using PHP if you have not checked then do check that first and then follow this tutorial.

I assume that you have already implemented the login register and email verification tutorial on your end and now want to have change password feature added to the same application, then let’s get started.

Process to change Current Password

Let me tell you the details on how you should proceed and what should be the use case while changing current password.

So basically first thing you will need is the active login users ID or Email so that you can find out old password (hash).

One you have old password or old password’s hash in hand then you can simply ask user to enter current password and validated it with the password that is stored in the database

This is actually a important step to protect user account security, so if any other person finds user account active and visits change password page then he can not modify password until and unless he know the current password. Good so far?

In next step let’s start implementing this use case.

Change Current Password

Open you project into your code editor, as I told you the project will same from the previous tutorial so the project folder structure will be the same, you can verify that from the following screen:

Project Folder Structure

Next open up profile.php file and add new anchor link in between logout button and email for change password page, to navigate.

profile.php:

 <p>Email <?php echo $user['email']; ?></p>

  <p><a href="change-password.php">Change Password</a></p>

   <br>
   Click here to <a href="logout.php">Logout</a>

Create and Design Change Password page:

We are going to need change password form so let’s create new page called change-password.php page into the root directory of the project and add following html script to design the UI:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change Password</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h2>
                Account activation process with email verification using PHP, MySQL and Swiftmailer
            </h2>
        </div>
    </div>
    <div class="form-group">
        Note: This is demo version from iTech Empires tutorials.
    </div>

    <div class="row">
        <div class="col-md-6">
                <div class="panel panel-default">
                <div class="panel-heading">
                    <a href="profile.php" class="pull-right">Back to Profile</a>    
                <h4>Change Password</h4></div>
                <div class="panel-body">

                     <?php
                    if ($error_message != '') {
                        echo '<div class="alert alert-danger"><strong>Error: </strong> ' . $error_message . '</div>';
                    }
                    if ($success_message != '') {
                        echo '<div class="alert alert-success"><strong>Success: </strong> ' . $success_message . '</div>';
                    }
                    ?>

                    <form action="change-password.php" method="post">
                        <div class="form-group">
                            <input type="password" name="current_password" class="form-control" placeholder="Current Password">
                        </div>
                        <div class="form-group">
                            <input type="password" name="new_password" class="form-control" placeholder="New Password">
                        </div>
                        <div class="form-group">
                            <input type="password" name="confirm_new_password" class="form-control" placeholder="Confirm New Password">
                        </div>
                        <div class="form-group">
                            <input type="submit" name="btnChangePassword" class="btn btn-primary" value="Change Password"/>
                        </div>
                    </form>
                </div>
                </div>
        </div>
    </div>
</div>
   
</body>
</html>

If you notice in the above script we have our form created along with three different fileds (Current Password, New Password and Confirm Password) this fields are going to help us take input from user.

You can navigate to change-password.php to see if the design as showing below in screen:

Change Password Form Design

Okay so we are good now will need to add new functions into the library file to handle change password request.

Go ahead and open up library.php file from lib folder and add following functions at the end of the DemoClass:

lib/library.php:

 /**
     * Verifies that a password matches a hash that is stored in database
     *
     * @param [type] $current_password
     * @param [type] $password_hash
     * @return void
     */    public function verifyCurrentPassword($current_password, $password_hash)
    {
        return password_verify($current_password, $password_hash);
    }

    /**
     * Change current password to new password
     *
     * @param [type] $id
     * @param [type] $new_password
     * @return void
     */    public function changeCurrentPassword($id, $new_password)
    {
        $id = mysqli_real_escape_string($this->db, $id);
        $password = mysqli_real_escape_string($this->db, $new_password);
        $password = password_hash($password, PASSWORD_DEFAULT, ['cost' => 11]);

        $query = "UPDATE `users` SET `password`='$password' WHERE `id` = '$id'";
        if (!$result = mysqli_query($this->db, $query)) {
            exit(mysqli_error($this->db));
        }

        return true;
    }

If you focus on a functions the first function is basically providing us support to match existing hash with the new password.

PHP provide us an inbuilt function called password_verify which does the matching process out of the box.

The other function is really simple we are just hashing password with password hash function and updating it into the database for the corresponding user ID.

Next will need to update existing function from DemoClass, it is a simple change, will need to update UserDetails() function to select additional field from the database:

lib/library.php:

/**
     * get user details
     *
     * @param $id
     *
     * @return array|null
     */    public function UserDetails($id)
    {
        $id = mysqli_real_escape_string($this->db, $id);
        $query = "SELECT `first_name`, `last_name`, `email`, `password`  FROM `users` WHERE `id` = '$id'";
        if (!$result = mysqli_query($this->db, $query)) {
            exit(mysqli_error($this->db));
        }
        $data = [];
        if (mysqli_num_rows($result) > 0) {
            while ($row = mysqli_fetch_assoc($result)) {
                $data = $row;
            }
        }

        return $data;
    }

Handle change password post request:

As you know we have added new form into the change-password.php which has post method, so now will need to handle the action to  and change the password.

Before going to do that here are required and important validation listed those we will be implementing while handling the request:

Change Password Request Validations:

  • Check to see all the fields are fill by user
  • Check if confirm password matches with new password.
  • Check if New Password entered by user is not matching with the value from the Current Password field – both the fields can not be same.
  • Verify that given current password is valid.

Let’s implement above validation and accept the change password request.

Go ahead and open up change-password.php page and add following script a the top of the page.

change-password.php:

<?php

// Start Session
session_start();

// check user login
if (empty($_SESSION['user_id'])) {
    header('Location: index.php');
}

// Application library ( with DemoLib class )
require __DIR__ . '/lib/library.php';
$app = new DemoClass();

$user = $app->UserDetails($_SESSION['user_id']);

$error_message = '';
$success_message = '';

if (!empty($_POST['btnChangePassword'])) {
    if ($_POST['current_password'] == '') {
        $error_message = 'Current Password field is required!';
    } elseif ($_POST['new_password'] == '') {
        $error_message = 'New Password field is required!';
    } elseif ($_POST['confirm_new_password'] == '') {
        $error_message = 'Please confirm your new password!';
    } elseif ($_POST['new_password'] != $_POST['confirm_new_password']) {
        $error_message = 'Password confirmation does not match with new password!';
    } elseif ($_POST['current_password'] == $_POST['new_password']) {
        $error_message = 'New Password and current password can not be the same!';
    } elseif (!$app->verifyCurrentPassword($_POST['current_password'], $user['password'])) {
        $error_message = 'Invalid current password, please enter valid password!';
    } elseif ($app->verifyCurrentPassword($_POST['current_password'], $user['password'])) {
        // update the current password and ask user to login again
        if ($app->changeCurrentPassword($_SESSION['user_id'], $_POST['new_password'])) {
            $success_message = 'Your password has been successfully change, please logout and login again with new password.';
        } else {
            $error_message = 'SERVER ERROR!!!';
        }
    }
}

?>

Now go ahead and test the implementation we are done with development, now your users can easily change there existing password.

Like share this tutorial or if you get any issues you can comment your question or feed back below.

Yogesh Koli

Software engineer & Blogger lives in India, has 6+ years of experience working with the front-end and back-end web app development.

View Comments

Recent Posts

Complete guide of using Laravel 6 Eloquent Subquery Enhancements

Learn How to use laravel frameworks new improved feature called Eloquent Subquery and get example of using Eloquent Subqueries and…

3 months ago

3 Useful examples of using Array Map function in PHP – Best Practices

Learn how to use php array map function with easy and essential tutorial to modify arrays in php here I…

3 months ago

Working with PHP Array Filter Function – Best Practices

Learn how to use php array filter function with easy and essential tutorial to filter array in php here I…

3 months ago

How to add Access Modifiers with Constructor Parameters in TypeScript

Want to know how to refactor your Typescript class, Learn here utilising Typescript of the best and essential feature that…

3 months ago

What is Access Modifiers and how to use Access Modifiers in TypeScript ?

What is Access Modifiers in typescript, how to use Access Modifiers, when to use them, what are the advantage of…

3 months ago

Top 10 Super Useful Packages to Improve Laravel applications in 2019

This tutorial provide ultimate list of package those are top 10 on packagist and super useful to optimize your laravel…

3 months ago