Use PHP Session to display the Username on Header after Login

We can display the logged-in user's name on the header after successful login using a PHP session. In your PHP code, check if the session variable for the username is set or not. If it is set, display it. In this tutorial, we will use PHP session to display the user name after login. We will also show the logout option after successful login. Checking the session variable is supposed to be very simple as below:


<?php 
if (isset($_SESSION['name']))
echo "Welcome ".$_SESSION['name']; 

To understand it in more detail, let us develop an application where the user can login into a system and after successful login, the user name will be displayed in the top right corner. So, let us develop a simple menu, a login form and the logout in PHP for complete understanding.

A screenshot is given below to get an idea of how it will look like:

Before Login display user name using php session after login

After Login display logged-in user information in PHP You can see that after login, the user name is displayed in the top right corner along with the Logout link.

You can also read the topic Login and Registration forms in PHP and MySQL with Session to know how this is applied in a Signup and Login system.

Watch YouTube Video

display name from php session variableFolders and Files

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

Display username on webpage after login in PHP

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:

Display Username After Login in PHP using session

Create a MySQL table to store user details

We will create a table named 'users' in a MySQL database. This table will have user details. We will be using a database called 'demo'. The table structure is given below:

PHP session

The table 'users' has 5 columns in it.

  1. id - it is the primary key and auto incremented
  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 used as information purpose only
You can use the below SQL script to create the table.

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;

Verify if data is inserted correctly after running the script, it should have the below data in it, signup_date should be the current date.

display name using session in php

Connect to MySQL database (dbconnect.php)

We will write a database connection script under the "cfg" folder and use it in other programs.

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 with four parameters.

For a 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.

Create a top menu (top_menu.php)

We will create a menu with Home and Login links on a menu bar. We will include this menu in other 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>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 the user is already logged in or not. If the user is logged in then the session variable $_SESSION['name'] will be set, in that case, display Logout only. But, if the user is not logged in, display Login only. This session variable 'name' is set in login.php discussed in the next step. Now, look at lines 27 and 28, we are displaying the user name if the user is logged in.

Develop a Login form (login.php)

Our Login form will have an email id and password for the user to login into the system.

displaying username on header when user logged in using php session

Let us take a 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 login 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 displayed are defined in the PHP code after the form is submitted. See the PHP code for login page 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 PHP session variables 'name' and 'userid' with the values of the user name and email id respectively.

Add CSS (style.css)

we will have style.css as given below and this is already added in top_menu.php.

style.css


* {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 the "active" class in our pages using jQuery. So, in style.css, properties for the "active" class are added.

Add JavaScript/jQuery (validation.js)

You have already seen togglePwd() function is called from the login form when the checkbox - "Show Password" is clicked. It is used to show and hide passwords. So, here is the code for it. We have written this in validation.js

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 the code for logout. Note that the home is added for navigation purposes only. See the below code:

index.php


<?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 active. For the home page, we add the class using the addClass() method. Similarly, in login.php also we will add the below script:


<script>
  $(document).ready(function() { 
        $("#login").addClass("active"); 
    });
</script>

Lastly, we will create logout.php as below:

logout.php


<?php
 session_start();
 session_unset();
 session_destroy();
 header("location:index.php");

Here, we delete all session variables using the session_unset() function. Then terminate the session using session_destroy().

Our development is complete, let us test the application now.

login form in php and sessionTest 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 below:

Display logged in user name using PHP Session

Now click on Login, and in the login form enter the email id as 'test@test.com' and the password as '123' to login. You should be able to login successfully and see the home page. The user name will be displayed along with the Logout link.

display logged-in user information in PHP

download source code to display user name from session after login in phpDownload Source Code

Download the source code from the download button below:

display user name from session after login in phpConclusion

In this example, I explained how to display the user name after a successful login in PHP along with a simple menu. We used PHP session to know if the user is logged in. I made it simple for you, you can always improve it. I hope it will be useful to you.

Post a Comment

Save my Name and Email id for future comments