How to develop change password in PHP and MySQL

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 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 code for login and logout also in this application.

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, user name will be displayed on the header after login.

Change password in PHP and mysql

You can also read below topics:

  1. Registration and Login forms with menu in PHP and MySQL
  2. How to display user name on header after login using PHP session

Change Login to logout after usersFolders and Files

Below is a screenshot of the folder structure and files we will be using:

change password code in php mysql using md5

We will be using a folder named 'change_pwd' under 'htdocs'. Not necessarily you have to create 'change_pwd' folder, you can use any folder you want.

  1. Folder 'cfg' is used for dbconnect.php used to connect to the MySQL database.
  2. Folder 'css' is for custom stylesheet
  3. 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 user logs in:

change login password in PHP and MYSQL

When user clicks on Change Password, below screen is displayed:

change login button to logout after the user login PHP

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. Table structure is given below:

Create Login Form Using PHP
  1. id - primary key
  2. email - email id of the user
  3. name - name of the user
  4. password - password for the user
  5. signup_date - date of signup, default is current date, this is for information purpose only

users.sql


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)

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.

  1. server - in our case it is localhost
  2. userid - we are using root user
  3. password - no password for user root
  4. 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 also 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 in those pages.

top_menu.php


<?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 user logs in we set session variables and display Login or Logout.

Create a PHP Login form (login.php)

Login form has email id and password for the user to login to the system. For login, we have to validate email id and password entered by the user against the values stored in the database.

Change User Password by Validating Current Password in PHP

login.php


<?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 top menu and our database connection php programs. A login form is defined. Once the form is submitted, it checks email and password from database. After successful login, email id and user name are added in two session variables and user is redirected to the home page.

Develop Change Password (change_pwd.php)

set login and logout in php

We will do some validation to check that passwords (password and confirm password) entered by the user are same. Also, we will check that new password is not same as the current password.

Let's see the code of my change password program.

change_pwd.php


<?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 user is logged in or not in line 5. Because user cannot change his/her password without login. If email session variable is set then user is logged in, else give message and redirect to 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 same. This function is defined under JavaScript file validate.js.

Once form is submitted, new password is checked with the current password. If it is different, new password is updated.

We have a simple home page (index.php) just to display success message.

index.php


<?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:

logout.php


<?php
if(!session_id()){
    session_start();
}
session_unset();
session_destroy();
header("location:index.php");

We are unsetting all session variables by using session_unset() function. Then deleting session using session_destroy() function. After session is deleted, user is logged out and redirected to the home page.

Add CSS (style.css)

We have already added style.css in top_menu.php.

style.css


* {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 togglePwd() function is called from login form when "Show Password" checkbox is clicked. Also, validate() function was called during change password form submission. Keep validate.js file in js folder.

validate.js


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 togglePwd() function, type of input object - password is changed from "text" to "password" and vice versa.

In validate() function, it checks if password and confirm password are same or not. If they are not same it returns false and the form is not submitted.

change php passwordTest the Application

Check in your XAMPP control panel and make sure services are running. Run localhost/change_pwd in the browser.

To login use email id as 'test@test.com', password as '123'. Click on Change Password and give a new password and submit. You will see successful message displayed as below:

Change password in PHP

To check the new password, logout and login again with new password.

write logout code in phpNote

In the Change Password form, we am not asking for current password as user is already logged in. However, for better security, you can have another field to enter current password. If current password matches, then only allow change password.

download source code for Change password in PHPDownload Source Code

You can download the source code by clicking on the Download button below.

login form in php and mysql source codeConclusion

Change Password is a basic requirement for any application. In real project there can be various other areas related to password policy, like user can not repeat any of the last 3 passwords or sending an email to the user as soon as password is changed. Here, we made it very simple for you, you can always improve it. Hope it will be useful to you.