How to Change Password in PHP

May 29, 2020
PHP
Change Password

Getting Started

I’ve used Bootstrap in this tutorial which is included in the downloadable, but if you want, you can download it yourself using this link.

Please take note that I’m using password_hash and password verify function which is available on PHP >=5.

Creating a Database

First, we create our database which contains our sample user.

I’ve included a SQL file in the downloadable of this tutorial. All you have to do is import the said file.

You should be able to create a database named dbase.

Creating a Login Form

Next, we create our sample login form. Please create a new file, name it as index.php and paste the codes below.

<?php
    session_start();
 
    //redirect to home if session has been set
    if(isset($_SESSION['user'])){
        header('location:home.php');
        exit();
    }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>How to Change Password using PHP</title>
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1 class="page-header text-center">Change Password using PHP</h1>
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4 panel panel-default" style="padding:20px;">
            <form method="POST" action="login.php">
                <p class="text-center" style="font-size:30px;"><b>Login</b></p>
                <hr>
                <div class="form-group">
                    <label for="username">Username:</label>
                    <input type="text" name="username" id="username" class="form-control">
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" name="password" id="password" class="form-control">
                </div>
                <button type="submit" name="login" class="btn btn-primary"><span class="glyphicon glyphicon-log-in"></span> Login</button>
            </form>
            <?php
                if(isset($_SESSION['error'])){
                    ?>
                    <div class="alert alert-danger text-center" style="margin-top:20px;">
                        <?php echo $_SESSION['error']; ?>
                    </div>
                    <?php
 
                    unset($_SESSION['error']);
                }
            ?>
        </div>
    </div>
</div>
</body>
</html>

Creating a Homepage

Next, we create the page where our verified users are direct. It also contains our change password form.

Please create a new file, name it as home.php and paste the codes below.

<?php
    session_start();
 
    if(isset($_POST['login'])){
        //connection
        $conn = new mysqli('localhost', 'root', '', 'dbase');
 
        //get the user with the username
        $sql = "SELECT * FROM users WHERE username = '".$_POST['username']."'";
        $query = $conn->query($sql);
        if($query->num_rows > 0){
            $row = $query->fetch_assoc();
            //verify password
            if(password_verify($_POST['password'], $row['password'])){
                $_SESSION['user'] = $row['id'];
            }
            else{
                $_SESSION['error'] = 'Password incorrect';
            }
        }
        else{
            $_SESSION['error'] = 'No account with that username';
        }
 
    }
    else{
        $_SESSION['error'] = 'Fill up login form first';
    }
 
    header('location: index.php');
 
?>

Creating a Change Password Script

Next, we create a script that changes the user’s password. Please create a new file, name it as change_password.php.

<?php
    session_start();
 
    if(isset($_POST['update'])){
        //get POST data
        $old = $_POST['old'];
        $new = $_POST['new'];
        $retype = $_POST['retype'];
 
        //create a session for the data incase error occurs
        $_SESSION['old'] = $old;
        $_SESSION['new'] = $new;
        $_SESSION['retype'] = $retype;
 
        //connection
        $conn = new mysqli('localhost', 'root', '', 'dbase');
 
        //get user details
        $sql = "SELECT * FROM users WHERE id = '".$_SESSION['user']."'";
        $query = $conn->query($sql);
        $row = $query->fetch_assoc();
 
        //check if old password is correct
        if(password_verify($old, $row['password'])){
            //check if new password match retype
            if($new == $retype){
                //hash our password
                $password = password_hash($new, PASSWORD_DEFAULT);
 
                //update the new password
                $sql = "UPDATE users SET password = '$password' WHERE id = '".$_SESSION['user']."'";
                if($conn->query($sql)){
                    $_SESSION['success'] = "Password updated successfully";
                    //unset our session since no error occured
                    unset($_SESSION['old']);
                    unset($_SESSION['new']);
                    unset($_SESSION['retype']);
                }
                else{
                    $_SESSION['error'] = $conn->error;
                }
            }
            else{
                $_SESSION['error'] = "New and retype password did not match";
            }
        }
        else{
            $_SESSION['error'] = "Incorrect Old Password";
        }
    }
    else{
        $_SESSION['error'] = "Input needed data to update first";
    }
 
    header('location: home.php');
 
?>

Creating a Logout Script

Lastly, we create our logout script. Please create a new file, name it as logout.php and paste the codes below.

<?php
    session_start();
    session_destroy();
    header('location: index.php');
?>

That ends this tutorial. Happy Coding!

Download Here

Leave a Reply

Your email address will not be published. Required fields are marked *