When a user logs into a web application, there should always be an option for the user to change the login password. In this topic, I will show how to write PHP code to change the password using MySQL database. Change password works for the current logged-in user who wants to change his/her password. So, we will see the PHP code for login and logout also.
The application will have a simple top menu where Login link will be displayed. After the user logs into the application, he/she can see links for change password and logout. Also, the user name will be displayed on the header after login.
You can also read below topics:
- Registration and Login Forms in PHP and MySQL with Session
- Display User Name on Header After Login Using PHP Session
Folders and Files
Below is the folder structure we will be using:
We will be using a folder named 'change_pwd' under 'htdocs'. It is not necessary to create 'change_pwd' folder only, you can use any folder you want.
- Folder 'cfg' is used for
dbconnect.php
used to connect to the MySQL database.
- Folder 'css' is for custom stylesheet
- Folder 'js' custom JavaScripts
We will use a menu bar(top_menu.php
) and there will be Home (index.php
) and Login (login.php
) on the menu. Below is the screenshot of the page after thr user logs in:
When the user clicks on Change Password, the below screen is displayed:
Create a MySQL table for the users
During login, userid (here email id will be used as userid) and password will be verified against the values in this table. The table structure is given below:
- id - primary key
- email - email id of the user
- name - name of the user
- password - password for the user
- signup_date - date of signup, default is current date, this is for information purpose only
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`signup_date` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `email`, `name`, `password`, `signup_date`) VALUES
(4, 'test@test.com', 'Test User', '202cb962ac59075b964b07152d234b70', '2021-10-13 00:00:00');
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Connect to MySQL database (dbconnect.php)
<?php
$server="localhost";
$userid="root";
$pwd="";
$dbname="demo";
$conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn)
die("Connection Error: " . mysqli_connect_error());
We are using mysqli_connect() function which needs 4 parameters.
- server - in our case it is localhost
- userid - we are using the root user
- password - no password for user root
- database name - demo in our case.
For a successful connection, $conn will be true and false otherwise. We will include dbconnect.php
in other php programs, we do not have to write it separately. You can read the topic How to connect to MySQL database in PHP using MySQLi and PDO.
Create a top menu (top_menu.php)
This is the top menu which will display the Menu items Home, Login, Change Password and Logout on a menu bar. We will include this menu in all the Home, Login and Change Password pages so that this menu will be visible on those pages.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
<meta name="description" content="">
<title><?php if (isset($_REQUEST['title'])) echo $_REQUEST['title']; else echo "Home";?></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/style.css">
<script src="js/validate.js"></script>
</head>
<body>
<div class="topmenu">
<div class="menubar" >
<a href="index.php?title=Home"><i class="fa fa-home"></i> Home</a>
<?php if (isset($_SESSION['name'])) { ?>
<div class="profile">
<div class="user">
<span style="color:#09fcf1;">Welcome <?php echo $_SESSION['name']; ?></span>
</div>
<a href="change_pwd.php?title=Change Password"><i class="fa fa-key"></i> Change Password</a>
<a href="logout.php"><i class="fa fa-sign-out"></i> Logout</a>
</div>
<?php }
else { ?>
<a id = "login" href="login.php?title=Login"><i class="fa fa-sign-in"></i> Login</a>
<?php } ?>
</div>
</div>
PHP session is used here for login and logout. Once the user logs in we set session variables and display Login or Logout.
Create a PHP Login form (login.php)
The login form has an email id and password for the user to login to the system. For login, we have to validate the email id and password entered by the user against the values stored in the database.
<?php
include 'top_menu.php';
include "cfg/dbconnect.php";
$email = $err_msg = "";
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($password);
$sql = "select * from users where email = '$email' and password = '$password'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$_SESSION['email'] = $email;
$_SESSION['name'] = $row['name'];
header("location:index.php");
}
else
$err_msg = "Incorrect Emailid/Password";
}
?>
<form class="form-1" action="login.php" method ="post">
<h2>Login Form</h2>
<?php if ($err_msg !="") ?>
<p class="err-msg"><?php echo $err_msg; $err_msg ="";?></p>
<div class="form-group col-md-12">
<label for="email">Email Id</label>
<input type = "text" class="form-control" name="email" id = "email" value="<?php echo $email;?>" placeholder ="Enter your Email Id" required autofocus>
</div>
<div class="form-group col-md-12">
<label for="password">Password</label>
<input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password" required>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary" name="submit">Login</button>
<a class="btn btn-danger" href="index.php">Cancel</a>
</div>
</form>
</body>
</html>
In the first two lines, I have added the top menu and our database connection PHP programs. A login form is defined. Once the form is submitted, it checks the email and password from the database. After successful login, email id and user name are added in two session variables and the user is redirected to the home page.
Develop Change Password (change_pwd.php)
We will do some validation to check that the passwords (password and confirm password) entered by the user are the same. Also, we will check that the new password is not the same as the current password.
Let's see the code of my change password program.
<?php
include 'top_menu.php';
include "cfg/dbconnect.php";
$email = $err_msg = "";
if (isset($_SESSION['email']))
$email = $_SESSION['email'];
else { ?>
<script>
alert("Your are not logged in");
location.href = "index.php";
</script>
<?php }
if (isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$password = md5($password);
// check if new password is same as existing password
$sql = "select * from users where email = '$email' and password = '$password'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0) // do not allow change password
$err_msg = "Password is same as existing password, please enter a new password";
else {
$sql = "update users set password = '$password' where email = '$email'";
$result = mysqli_query($conn,$sql);
if ($result) {
$_SESSION['succ_msg'] = "Your Password is changed successfully";
header("location:index.php");
}
else
$err_msg = "Error in changing Password, please try after sometime";
}
} ?>
<form class="form-1" action="change_pwd.php" method ="post" onsubmit="return validate()">
<h2>Change Password Form</h2>
<p>Change Pssword for <?php echo $email;?></p>
<?php if ($err_msg !="") ?>
<p class="err-msg"><?php echo $err_msg; $err_msg ="";?></p>
<input type = "hidden" name="email" id = "email" value="<?php echo $email;?>">
<div class="form-group col-md-12">
<label>New Password</label>
<input type = "password" class="form-control" name="password" id = "password" maxlength="20" placeholder ="Enter New Password" required autofocus>
</div>
<div class="form-group col-md-12">
<label>Confirm Password</label>
<input type = "password" class="form-control" name="conf_password" id = "conf_password" maxlength="20" placeholder ="Confirm Password" required>
</div>
<div class="col-md-12 form-group">
<input type="checkbox" class="check" onclick="togglePwd()">Show Password
</div>
<div class="form-group col-md-12 text-center">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
<a class="btn btn-danger" href="index.php">Cancel</a>
</div>
</form>
</body>
</html>
We are checking if the user is logged-in first in line 5. Because the user cannot change his/her password without login. If the email session variable is set then the user is logged-in, else give a message and redirect the user to the home page.
We are using a JavaScript function called validate() on the onSubmit event of the form. This is to check if both passwords entered by the user are the same. This function is defined under JavaScript file validate.js
.
Once the form is submitted, the new password is checked with the current password. If it is different, the new password is updated.
We have a simple home page (index.php
) just to display a success message.
<?php
include 'top_menu.php';
?>
<div class="container">
<h1>Home</h1>
<h2>Change password using PHP and MySQL</h2>
<?php if (isset($_SESSION['succ_msg'])) { ?>
<div class="alert alert-success alert-dismissible succ-msg">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo $_SESSION['succ_msg'];
unset($_SESSION['succ_msg']);
?>
</div>
<?php } ?>
</div>
</body>
</html>
Lastly, here is logout.php
:
<?php
if(!session_id()){
session_start();
}
session_unset();
session_destroy();
header("location:index.php");
We are unsetting all session variables by using the session_unset()
function. Then deleting the session using the session_destroy()
function. After the session is deleted, the user is logged out and redirected to the home page.
Add CSS (style.css)
We have already added style.css
in top_menu.php
.
* {box-sizing: border-box;
}
h1, h2 {
text-align: center;
margin-top: 20px;
}
.topmenu {
overflow: hidden;
background-color: #0a68b0;
}
.topmenu a , .topmenu .user{
float: left;
display: block;
font-size: 17px;
color: #fff;
padding: 17px 20px;
text-decoration: none;
text-align: center;
}
.topmenu .menubar {
padding-left: 20px;
}
.topmenu a.active {
background-color: #4e69cc;
color: #000;
}
.topmenu a:hover {
background-color: #4e69cc;
color: black;
}
@media screen and (max-width: 500px) {
.topmenu a {
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
display: block;
float: none;
}
}
.err-msg{
text-align: center;
color:red;
}
.succ-msg{
width: 50%;
margin: auto;
}
.form-1 {
margin: 50px auto;
padding-bottom: 30px;
border: 1px solid #09168d;
border-radius: 7px;
background: #fff;
width: 37%;
}
.check {
margin: 5px 0px;
width: 6%;
height: 20px;
}
.welcome{
color: #c6f606;
}
.profile{
float: right;
}
p{
text-align: center;
color: #1212f2;
}
You can see simple styles are added here. Keep this style.css file in your css folder.
Add JavaScript/jQuery (validate.js)
You have already seen the togglePwd()
function is called from the login form when the "Show Password" checkbox is clicked. Also, validate()
function was called during the change password form submission. Keep validate.js
file in the "js" folder.
function togglePwd() {
// get the objects password and confirm password in two varibles
var pwd = document.getElementById("password");
var c_pwd = document.getElementById("conf_password");
if (pwd.type === "password")
pwd.type = "text";
else
pwd.type = "password";
if (c_pwd.type === "password")
c_pwd.type = "text";
else
c_pwd.type = "password";
}
function validate() {
// check if both passwords are same
var password = document.getElementById("password").value;
var conf_password = document.getElementById("conf_password").value;
if (password != conf_password) {
alert("Passwords do not match!");
document.getElementById("password").focus();
return false;
}
}
In the togglePwd()
function, the type of input object - password is changed from "text" to "password" and vice versa.
In the validate()
function, it checks if the password and the confirm password are the same. If they are not the same it returns false and the form is not submitted.
Test the Application
Check in your XAMPP control panel and make sure services are running. Run localhost/change_pwd in the browser.
To login use the email id as 'test@test.com', the password as '123'. Click on Change Password and give a new password and submit. You will see a successful message displayed as given below:
To check the new password, logout and login again with the new password.
Post a Comment