When a user logs in successfully into a web application, we can use PHP $_SESSION
to store user name in a session variable and display on the header. In you PHP code just check if session variable is set or not. If it is set, just display it. In this tutorial we will use PHP session to display the user name after login. We will also show Logout option after successful login. Checking if session variable is available is supposed to be very simple as below:
<?php
if (isset($_SESSION['name']))
echo "Welcome ".$_SESSION['name'];
?>
To understand it in more details, let us develop an application where user can login into a system and after successful login, user name will be displayed on top right corner. So, let us develop a simple menu, a login form and logout PHP code for complete understanding.
A screenshot is given below to get an idea of how it will look like:
Before Login
After Login
You can see after login, user name is displayed on top right corner along with Logout link.
You can also read below topics to get more details about Signup and Login.
- Registration and Login forms with in PHP and MySQL with Session
Folders and Files
Below is a screenshot of folder structure and files I am using:
We will use a folder called 'login' under 'htdocs'.
'cfg' folder is used to keep dbconnect.php
used to connect to the MySQL database.
Folder 'css' is for custom stylesheet
Folder 'js' is for our custom JavaScripts
A menu bar(top_menu.php
) will be displayed on the top and there will be links for Home (index.php
) and Login (login.php
). Below is the screenshot of the login page:
Step 1 - Create a MySQL table to store user details
We will create a table named 'users' in MySQL database. This table will have user details. We will be using a database called 'demo'. Table structure is given below:
The table 'users' has 5 columns in it.
- id - it is the primary key and auto incremented
- 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 used as information purpose only
You can use below SQL script to create the table.
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;
Verify if data is inserted correctly after running the script, it should have below data in it, signup_date should be the current date.
Step 2 - Connect to MySQL database (dbconnect.php)
We will write database connection script under "cfg" folder and use it in other programs.
<?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 with four parameters.
For successful connection $conn
will be true. To know more about database connection, you can read the topic How to connect to MySQL database in PHP using MySQLi and PDO.
Step 3 - Create a top menu (top_menu.php)
We will create a menu with Home and Login links on a menubar. We will include this menu in other 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>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.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="js/validation.js"></script>
</head>
<body>
<div class="topmenu">
<div class="menubar" >
<a id = "home" href="index.php"><i class="fa fa-home"></i> Home</a>
<?php if (isset($_SESSION['name'])) { ?>
<div class="logout">
<a href="logout.php"><i class="fa fa-sign-out"></i> Logout</a>
</div>
<?php }
else { ?>
<a id = "login" href="login.php"><i class="fa fa-sign-in"></i> Login</a>
<?php } ?>
<div class="user"><?php if (isset($_SESSION['name']))
echo '<span class="welcome">Welcome </span>'.$_SESSION['name']; ?>
</div>
</div>
</div>
You can see for Logout and Login, we must check if user is already logged in or not. If user is logged in then session variable 'name' will be set, in that case display Logout only. But, if user is not already logged in, display Login only. This session variable 'name' is set in login.php
discussed in next step. Now, look at line 27 and 28, we are displaying user name if user is logged in.
Step 4 - Develop a Login form (login.php)
Our Login form will have email id and password for the user to login to the system.
Let us look at the code for the login form.
<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>
It is a simple form with email and password as input fields with a submit button. There is a show password checkbox, we will write the JavaScript on the onClick event of this checkbox. Error messages that are displayed are defined in the PHP code after the form is submitted. See the code for processing login form below:
<?php
include 'top_menu.php';
include "cfg/dbconnect.php";
// Initilize varibles
$email = $err_msg = "";
if (isset($_POST['submit'])) { // if Form is submitted
// store form data into variable
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// generate md5 hash, because password is stored in database with md5 hash
$password = md5($password);
// check if same emailid and password are stored in the database
$sql = "select * from users where email = ? and password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $email, $password);
if ($stmt->execute()){
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
$_SESSION['name'] = $row['name'];
$_SESSION['userid'] = $email;
header("location:index.php");
}
else
$err_msg = "Incorrect Email id/Password";
}
else
$err_msg = "Some Error occurred";
}
?>
After successful login, we create two session variables 'name' and 'userid' with the values of user name and email id respectively.
Step 5 - Add CSS (style.css)
we will have style.css
as below and this is already added in top_menu.php
.
* {box-sizing: border-box;
}
body {
margin: 0;
font-family: Helvetica, sans-serif;;
}
h1, h2 {
text-align: center;
margin-top: 20px;
}
.topmenu {
overflow: hidden;
background-color: #0a68b0;
}
.topmenu a {
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;
}
.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;
}
.user{
float: right;
padding: 17px 25px;
color: #fff;
}
.welcome{
color: #c6f606;
}
.logout{
float: right;
}
We have added simple styles here. Note that we added "active" class in our pages using jQuery, so, in style.css
, properties for "active" class are added.
Step 6 - Add JavaScript/jQuery (validation.js)
You have already seen togglePwd()
function is called from login form when checkbox - "Show Password" is clicked. It is used to show and hide password. So, here is the code for it. We have written this in validation.js
function togglePwd() {
// get the password object into a variable
var pwd = document.getElementById("password");
if (pwd.type === "password")
pwd.type = "text";
else
pwd.type = "password";
}
We are just changing the type of input password field from "password" to "text" and vice versa.
Now, we will add a simple Home page and code for logout. Remember that Home page is not a complete Home page, it is added just for navigation purpose only. See below code:
<?php
include 'top_menu.php';
?>
<h1> You are at Home Page </h1>
<script>
$(document).ready(function() {
$("#home").addClass("active");
});
</script>
</body>
</html>
See the jQuery script to make the selected menu item as active. Here, for Home page we are adding the class using addClass()
method. Similarly, in login.php
also we will add below script:
<script>
$(document).ready(function() {
$("#login").addClass("active");
});
</script>
Lastly, we will create logout.php
as below:
<?php
session_start();
session_unset();
session_destroy();
header("location:index.php");
?>
Here, we are deleting all session variables by using session_unset()
function. Then terminate the session using session_destroy()
.
Our development is complete, let us test the application now.
Test the Application
Make sure Apache and MySQL services are running in your XAMPP control panel. Run localhost/login in the browser. You will see the home page displayed as below:
Now click on Login, and in the login form enter email id as 'test@test.com', password as '123' to login. You should be able to login successfully and see the home page. User name will be displayed along with Logout link.
Hope you understood how the application works now.