How to code Login, Logout and Change Password in PHP and MySQL

Developing a login system for a web application is the most important part of the project. Here, you need to have a proper authenticating system to make sure only authorized users can login into the system.

In this topic, we will develop login, logout and change password for an web application using PHP and MySQL with some JavaScripts. Just for demo purpose, we will have a simple top menu in which Login link will be displayed. After user logs into the application, he/she can see the links for change password and logout. Also, user name will be displayed in the top menu after login.

simple login form in php with sessionFolders and Files

login form in php and mysql source code

We will be using a folder called 'login' under 'htdocs' as I am using XAMPP.

  1. 'cfg' folder is used for dbconnect.php to connect to the MySQL database.
  2. 'css' folder for custom stylesheet
  3. 'js' folder is for our custom JavaScripts

We will create a menu(top_menu.php) and there will be links for Home (index.php) and Login (login.php). Below is the login page:

login, logout and Change password form in PHP

When the user logs in, we will be seeing this page:

Changing a password PHP MySQL

Create a MySQL table for user details

Create the table named 'users' in MySQL database. Table structure is given below:

change login password in PHP and MYSQL

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
(1, '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=2;

Connect to MySQL database (dbconnect.php)

We will create a separate php program to connect to the database and use it in all other programs where database connection is needed.

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() method with 4 parameters as given below:

  1. server - localhost
  2. userid - we are using root user
  3. password - no password for the user root
  4. database name - our database name is "demo".

You can also read the topic How to connect to MySQL database in PHP using MySQLi and PDO for database connection using PHP.

Create a top menu (top_menu.php)

The top menu will display the Menu items - Home, Login, Change Password and Logout on a menu bar.

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>

We have added links for Home, Login, Change Password and Logout. Once user logs in we will set session variables. So, by checking session variables, we are displaying Change Password and Logout.

Create a Login form (login.php)

We will use email id and password to login into the system.

Login form in PHP

Let us look at the code for login.php

login.php


<?php
include 'top_menu.php';
include "cfg/dbconnect.php";

 // Initilize varibles
$email = $succ_msg = $err_msg = "";  
if (isset($_POST['submit'])) {    // if Form is submitted
	// store form data into variable
	$email = $_POST['email'];
	$password = $_POST['password'];
	// encrypt passsword
	$password = md5($password);
	
	// check if same emailid and password are stored in teh database
	$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['name'] = $row['name'];
		$_SESSION['userid'] = $email;
		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="col-md-12 form-group">
	 		<label>Email Id</label>
	 		<input type = "text" class="form-control" name="email" id = "email" value="<?php echo $email;?>" placeholder ="Enter your Email Id" required>
	 	</div>

	 	<div class="col-md-12 form-group">
		 	<label>Password</label>
		 	<input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password" required>
		 </div>
	 	
	 	<div class="col-md-12 form-group">
	 		<input type="checkbox" class="check" onclick="togglePwd()">Show Password
	 	</div>
	 	<div class="col-md-12 form-group text-right">
	 		<button type="submit" class="btn btn-primary" name="submit">Login</button>
	 	</div>
	 </form>
<script>
  $(document).ready(function() { 
       $("#login").addClass("active"); 
    });
</script>
</body>
</html>

It is a simple form, we are checking the input values with data in 'users' table. After successful login assigning email id and user name in two session variables and redirecting user to the home page.

Develop Change Password (change_pwd.php)

Login form in PHP

Let's see the code for 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 that passwords (password and confirm password) entered by the user are the same. Also, new password should not be the same as the current password.

validate() function is called after the form is submitted to check if both the passwords are same. This function is defined in validate.js.

In the form, we have used a hidden input field email for which password will be updated and two input fields for the new password.

We have a simple home page (index.php) to show the success message.

index.php


<?php 
include 'top_menu.php';
?>
<div class="container">
	<h1>Home</h1>
	<h2>Login, Logout and 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> 

We are checking if 'succ_msg' session variable is set. Then displaying it using Bootstrap alert.

Below is the code for logout.php as below:

logout.php


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

session_unset() deletes all session variables. session_destroy() deletes the session. User is logged out and redirected to the home page.

Add CSS (style.css)

style.css is included in top_menu.php.

style.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;
}

Add JavaScript/jQuery (validate.js)

togglePwd() function is used for "Show Password". validate() function is called after form submission.

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;
	}
}

php login sessionTest the Application

Run localhost/login. Home page will be displayed. See the below screen:

Login using email id as 'test@test.com', password as '123'. After login you should see user name is displayed. Click on Change Password and give a new password and submit.

Change Login to logout after user login using php session

PHP Login logout example with sessionNote

  1. We have not enforced any password rules here.
  2. For better security, you can add an input password field to get the current password. If it matches then only you should proceed for change password.
  3. Even though two passwords are validated in the JavaScript, this is verified again in php code. You can use one of them. However, server side validation is always better than client side validation.

Creating a User Login System with PHP and MySQLDownload Source Code

Download the source code using the download button below:

login, logout and change password in php and mysqlConclusion

Login, Logout and Change Password are the basic requirements for any application. We have seen how these can be developed in PHP as a beginner. Here, we made it very simple for you, you can always improve it. Hope, it will be useful for you.