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 using PHP and MySQL with some JavaScript. For demo purposes, we will have a simple top menu with Login link. Change password and logout options will be visible only after login. The user name will be displayed on the top menu after a successful login.
Folders and Files
We will be using a folder called 'login' under 'htdocs' as I am using XAMPP.
- 'cfg' folder is used for
dbconnect.php
to connect to the MySQL database.
- 'css' folder for custom stylesheet
- '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:
When the user logs in, we will be seeing this page:
Create a MySQL table for user details
Create the table named 'users' in MySQL database. Table structure is given below:
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.
<?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:
- server - localhost
- userid - we are using root user
- password - no password for the user root
- 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.
<?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.
Let us look at the code for 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)
Let's see the code for 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 that passwords (password and confirm password) entered by the user are the same. Also, the 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 the same. This function is defined in validate.js
.
In the form, we have used a hidden email input field and two input fields for the new password.
We have a simple home page (index.php
) to show the success message.
<?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:
<?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
.
* {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 the form submission.
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;
}
}
Post a Comment