How to display logged in user information in PHP ?

24 Nov, 2021
In social networking websites like Facebook, Instagram, etc, the username and profile picture of the user that has logged in gets displayed in the header of the website, and that header remains constant, irrespective of the webpage the user has opened. Such functionality can be created by using the session variables. Session variables exist only while the user’s session is active. After the session is complete, the session variables get destroyed. These are unique for each visitor and are generally used to store user-specific information such as the username, profile picture etc, once the user logs in. The session variables are used to display logged in user information in PHP.Project Explanation and Code: This is a simple registration system. The register.php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index.php page where a welcome message and the username of the logged-in user is displayed.The first step is to create a database, and then a table inside it. The database is named ‘registration’, and the table is named ‘users’. The ‘users’ table will contain 4 fields. 
id – primary key – auto incrementusername – varchar(100)email – varchar(100)password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table:  
id – primary key – auto increment
username – varchar(100)
email – varchar(100)
password – varchar(100)The ‘id’ will be the primary key, it means that it will be unique for every registered user. It will also auto-increment for every new registration. The data type for username, email and password will be varchar. The size can be adjusted as per the requirement however, 100 is sufficient.SQL code for the table:  
sql
CREATE TABLE `users` (    `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,    `username` varchar(100) NOT NULL,    `email` varchar(100) NOT NULL,    `password` varchar(100) NOT NULL)
phpMyAdmin after the database and table creation
Project folder, containing the necessary files
html
<?php  if (count($errors) > 0) : ?>    <div class="error">        <?php foreach ($errors as $error) : ?>           <p><?php echo $error ?></p>           <?php endforeach ?>    </div><?php  endif ?>
Explanation: The error.php file is responsible for holding the error messages of the system. Suppose the user enters the wrong username and password combination, then in such cases, the error messages will be stored in the $error variable, which will then be displayed to the user using ‘echo; function of PHP.server.php 
php
<?php // Starting the session, necessary// for using session variablessession_start();  // Declaring and hoisting the variables$username = "";$email    = "";$errors = array();$_SESSION['success'] = "";  // DBMS connection code -> hostname,// username, password, database name$db = mysqli_connect('localhost', 'root', '', 'registration');  // Registration codeif (isset($_POST['reg_user'])) {      // Receiving the values entered and storing    // in the variables    // Data sanitization is done to prevent    // SQL injections    $username = mysqli_real_escape_string($db, $_POST['username']);    $email = mysqli_real_escape_string($db, $_POST['email']);    $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);    $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);      // Ensuring that the user has not left any input field blank    // error messages will be displayed for every blank input    if (empty($username)) { array_push($errors, "Username is required"); }    if (empty($email)) { array_push($errors, "Email is required"); }    if (empty($password_1)) { array_push($errors, "Password is required"); }      if ($password_1 != $password_2) {        array_push($errors, "The two passwords do not match");        // Checking if the passwords match    }      // If the form is error free, then register the user    if (count($errors) == 0) {                 // Password encryption to increase data security        $password = md5($password_1);                 // Inserting data into table        $query = "INSERT INTO users (username, email, password)                  VALUES('$username', '$email', '$password')";                 mysqli_query($db, $query);          // Storing username of the logged in user,        // in the session variable        $_SESSION['username'] = $username;                 // Welcome message        $_SESSION['success'] = "You have logged in";                 // Page on which the user will be        // redirected after logging in        header('location: index.php');    }}  // User loginif (isset($_POST['login_user'])) {         // Data sanitization to prevent SQL injection    $username = mysqli_real_escape_string($db, $_POST['username']);    $password = mysqli_real_escape_string($db, $_POST['password']);      // Error message if the input field is left blank    if (empty($username)) {        array_push($errors, "Username is required");    }    if (empty($password)) {        array_push($errors, "Password is required");    }      // Checking for the errors    if (count($errors) == 0) {                 // Password matching        $password = md5($password);                 $query = "SELECT * FROM users WHERE username=                '$username' AND password='$password'";        $results = mysqli_query($db, $query);          // $results = 1 means that one user with the        // entered username exists        if (mysqli_num_rows($results) == 1) {                         // Storing username in session variable            $_SESSION['username'] = $username;                         // Welcome message            $_SESSION['success'] = "You have logged in!";                         // Page on which the user is sent            // to after logging in            header('location: index.php');        }        else {                         // If the username and password doesn't match            array_push($errors, "Username or password incorrect");        }    }}  ?>
Explanation: The session is started using session_start() method. After that, the variables are declared and an error array is created. It will store all the error messages. The server.php page is then connected to the ‘registration’ database created earlier. After the user clicks the ‘register’ button on the register.php button, the data entered is sent to the database, and this completes a new registration. However, form validation is done before that to make sure that the user is filling the form correctly. All the fields are required and cannot be left blank.Line 18 – 21: mysqli_real_escape_string escapes the special characters before sending the data to the database. This is essential for database security from SQL injections.Line 25 – 27: These lines makes sure that the user is filling all the input boxes, and whether the ‘password’ and ‘confirm password’ matches. If both the password matches, then the code further runs.Line 29 – 32: Checking whether the password matches or not. Line 35 – 46: If the number of errors until this point is zero, the password is then ‘md5’ encrypted and the data entered is sent to the database. After the registration process is complete, the username is stored in the session variable, and the user is redirected to the index.php page, where he is asked to enter the login credentials.Line 50 – 80: First the username and password entered in sanitized. This is essential to increase database security, as it eliminates the chances of any SQL injection. The user gets an error message if the username or the password field is left blank. If the number of errors until this point of code is found to be 0, then a database check is run. If the username entered by the user is found to be present in the database, then the user successfully logs in. The user is then redirected to the ‘index.php’ page.login.php  
html
<?php include('server.php') ?><!DOCTYPE html><html><head>    <title>        Login and Registration        System - LAMP Stack    </title>         <link rel="stylesheet" type="text/css"            href="style.css"></head><body>    <div class="header">        <h2>Login Here!</h2>    </div>          <form method="post" action="login.php">          <?php include('errors.php'); ?>          <div class="input-group">            <label>Enter Username</label>            <input type="text" name="username" >        </div>        <div class="input-group">            <label>Enter Password</label>            <input type="password" name="password">        </div>        <div class="input-group">            <button type="submit" class="btn"                        name="login_user">                Login            </button>        </div>           <p>            New Here?            <a href="register.php">                Click here to register!            </a>        </p>       </form></body> </html>
Explanation: Login page of the system. The user has to enter the username and password to successfully log in. After the login button is pressed, the login code written in the server.php page is run, which does all the backend work, like checking whether the username and password match or not.register.php  
php
<?php include('server.php') ?><!DOCTYPE html><html><head>    <title>        Registration system PHP and MySQL    </title>    <link rel="stylesheet" type="text/css"                    href="style.css"></head> <body>    <div class="header">        <h2>Register</h2>    </div>          <form method="post" action="register.php">          <?php include('errors.php'); ?>          <div class="input-group">            <label>Enter Username</label>            <input type="text" name="username"                value="<?php echo $username; ?>">        </div>        <div class="input-group">            <label>Email</label>            <input type="email" name="email"                value="<?php echo $email; ?>">        </div>        <div class="input-group">            <label>Enter Password</label>            <input type="password" name="password_1">        </div>        <div class="input-group">            <label>Confirm password</label>            <input type="password" name="password_2">        </div>        <div class="input-group">            <button type="submit" class="btn"                                name="reg_user">                Register            </button>        </div>           <p>            Already having an account?            <a href="login.php">                Login Here!            </a>        </p>       </form></body></html>
Explanation: This page contains the HTML coding of the registration page. The ‘server.php’, and ‘errors.php’ pages are included in lines 01 and 15 respectively. This is necessary to make the backend of the registration system work. The user is asked to enter the username, email, and password to create an account. After the input fields are filled, the data entered is sent to the database table.index.php  
html
<?php // Starting the session, to use and// store data in session variablesession_start();  // If the session variable is empty, this// means the user is yet to login// User will be sent to 'login.php' page// to allow the user to loginif (!isset($_SESSION['username'])) {    $_SESSION['msg'] = "You have to log in first";    header('location: login.php');}  // Logout button will destroy the session, and// will unset the session variables// User will be headed to 'login.php'// after logging outif (isset($_GET['logout'])) {    session_destroy();    unset($_SESSION['username']);    header("location: login.php");}?><!DOCTYPE html><html><head>    <title>Homepage</title>    <link rel="stylesheet" type="text/css"                    href="style.css"></head><body>    <div class="header">        <h2>Home Page</h2>    </div>    <div class="content">          <!-- Creating notification when the                user logs in -->                 <!-- Accessible only to the users that                have logged in already -->        <?php if (isset($_SESSION['success'])) : ?>            <div class="error success" >                <h3>                    <?php                        echo $_SESSION['success'];                        unset($_SESSION['success']);                    ?>                </h3>            </div>        <?php endif ?>          <!-- information of the user logged in -->        <!-- welcome message for the logged in user -->        <?php  if (isset($_SESSION['username'])) : ?>               <p>                Welcome                <strong>                    <?php echo $_SESSION['username']; ?>                </strong>            </p>                  <p>                <a href="index.php?logout='1'" style="color: red;">                    Click here to Logout                </a>            </p>           <?php endif ?>    </div></body></html>
Explanation: Line 01 – 19: The username that was stored in the session variable is now displayed back to the user. This session variable can either be destroyed using unset($_SESSION[“products”]) or session_destroy(). However, session_destroy() will destroy all the session variables at once. To destroy only the ‘username’ session variable, it will be better to unset the variable using unset($_SESSION[“products”]).Line 34 – 42: This makes sure that this page is accessible only to those users that are logged in.Line 45 – 50: This displays a personalized welcome message to the user once they log in.CSS File 
CSS
* {    margin: 0px;    padding: 0px;}body {    font-size: 120%;    background: #F8F8FF;} .header {    width: 30%;    margin: 50px auto 0px;    color: white;    background: #5F9EA0;    text-align: center;    border: 1px solid #B0C4DE;    border-bottom: none;    border-radius: 10px 10px 0px 0px;    padding: 20px;}form, .content {    width: 30%;    margin: 0px auto;    padding: 20px;    border: 1px solid #B0C4DE;    background: white;    border-radius: 0px 0px 10px 10px;}.input-group {    margin: 10px 10px 10px 10px;} .input-group label {    display: block;    text-align: left;    margin: 5px;    font-size: 20px;}.input-group input {    height: 32px;    width: 95%;    padding: 5px 10px;    font-size: 15px;    border-radius: 10px;    border: 1px solid gray;}.btn {    cursor: pointer;    padding: 12px;    font-size: 16px;    color: white;    background: #23585a;    border: none;    border-radius: 10px;}.error {    width: 92%;    margin: 0px auto;    padding: 10px;    border: 1px solid #a94442;    color: #a94442;    background: #f2dede;    border-radius: 5px;    text-align: left;}.success {    color: #3c763d;    background: #dff0d8;    border: 1px solid #3c763d;    margin-bottom: 20px;}
Pictorial Representation: 
Registration Page
 
User is redirected to this page after logging in. A welcome message is displayed there.
 
Login page of the system
 
User has successfully logged in
 
Incorrect username and password combination
 
The source codes of this project can be obtained from this GitHub repository.After downloading and unzipping the project, follow the given steps to run the program: 
Download all the files, or clone the repository into your local system.
Create a database named ‘registration’, and a table named ‘users’. The MySQL code of the table has been provided above.
Use XAMP or WAMP to run the system on localhost.
Make sure that the necessary ports to run Apache and MySQL server are free. If not, then you will have to change the port numbers.
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
arorakashish0911
kalrap615
sagar0719kumar
HTML-Misc
PHP-basics
Picked
HTML
PHP
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.