The Wayback Machine - https://web.archive.org/web/20240911195550/https://www.geeksforgeeks.org/how-to-display-logged-in-user-information-in-php/
Open In App

How to display logged in user information in PHP ?

Last Updated : 24 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

  1. id – primary key – auto increment
  2. username – varchar(100)
  3. email – varchar(100)
  4. 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

error.php

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 variables
session_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 code
if (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 login
if (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 variable
session_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 login
if (!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 out
if (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

 

How to run this project?

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.



Previous Article
Next Article

Similar Reads

If we delete cookies of a site, we can still logged in without logging again
The facebook is coded in PHP and PHP was launched in 1994. But in PHP, there is a disadvantage i.e if we disable cookies (say in Facebook) the Facebook server will forget the person who has logged in previously and it will take to me that page when that application was launched for the first time. But in Java (JEE Edition, launched in 1999) we have
6 min read
How to create HTML form that accept user name and display it using PHP ?
Through HTML forms various data can be collected from the user and can be sent directly to the server through PHP scripting. There are basically two methods for sending data to the server one is "GET" and the other one is "POST". In GET method, the data goes through the browser's URL and can be seen by anyone using the browser, and it is not very s
2 min read
Which tag is used to display additional information when we click to open or close on demand in HTML ?
HTML provides many predefined tags which have some specific functionality for the contribution of developing web pages. In this article, we will learn how to show the additional information when the user clicks to open or close on demand in HTML. This can be simply done with the help of the HTML &lt;details&gt; tag in the document. This tag is used
1 min read
How to display child row information using jQuery DataTables plugin ?
DataTables are modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. DataTable is a simple-to-use jQuery plug-in with many options for developer's custom changes. Some features of DataTables are pagination, searching, sorting and multiple column ordering. In this article, we will learn to use DataTable AP
4 min read
What is the difference between display: inline and display: inline-block in CSS?
The display property in CSS is a very useful and commonly used property that contains many values. The display property defines how an HTML element should be displayed on the webpage. The property also specifies the type of box used for an HTML element and how it should be laid out on the page. If we need to display the elements that are laid out a
4 min read
How display: inline is different from display: inline-block in CSS ?
In this article, we will know about the display property in CSS, along with understanding the 2 different property values for display property, i.e., display: inline &amp; display: inline-block properties, &amp; will understand their basic differences &amp; implementation through the examples. The display property facilitates setting the element by
3 min read
What is the difference between display:inline-flex and display:flex in CSS ?
In this article, we will see the display property &amp; its values, i.e. the inline-flex &amp; flex, in order to specify the display behavior of an element, along with understanding their basic differences &amp; will illustrate them through the examples. Both CSS display: inline-flex and display: flex properties are used to create flexible layouts.
3 min read
How to display hidden element when a user starts typing using JavaScript ?
Method 1: Using the oninput attribute to input element: The oninput attribute is fired whenever user starts typing to the input element. This can be used to detect changes in a &lt;input&gt; or &lt;textarea&gt; element. A function is called with the value of this attribute. This function selects the hidden element and changes its display property t
3 min read
How to apply box-shadow to display elements like single element to user in CSS ?
In CSS, the box-shadow property allows you to add a shadow effect to an element. However, when it comes to applying box shadow to a combination of elements such as a &lt;span&gt; and &lt;input&gt;, it can be a bit tricky to get the desired effect. In this article, we will discuss how to apply box-shadow to a &lt;span&gt; &lt;input&gt; combination s
2 min read
User to User private Chat App using ReactJS and Firebase | Without socket programming
This article covers how to make a User to User private Chat App using React JS and Firebase (without socket programming). React is a JavaScript framework provided by Facebook and is used to build fully-featured web applications. We will be following the below steps for creating our application: npx create-react-app chat-appcd chat-appNow install al
10 min read
How to Get PHP Configuration Information using phpinfo()?
The phpinfo() function in PHP gives us the details about the PHP version and configuration installed in our system. To check the Configurations and Versions, a simple PHP script can be used. The script consists of a PHP function called "phpinfo()" which outputs information about PHP's configuration. The phpinfo() function is also useful in the debu
2 min read
How to get uploaded file information in Receiving Script in PHP ?
In this article, we will know how to get the uploaded file information in the receiving script in PHP. When a document/file is uploaded to any application or any browser and to know the basic information of a file like a file name, type of file, and how many bytes are present in the file, PHP offers a predefined array called $_FILES that allows the
3 min read
How to get information sent via post method in PHP ?
In this article, we will learn to get information via the post method in PHP. In PHP, we can use the $_POST method as a superglobal variable that is operated to manage form data. After we click on submit button and the page will send the data through the post method. We can use the data after storing it in a variable according to our requirements.
2 min read
How do I get PHP errors to display?
There are four ways to display errors in PHP which are listed below: error_reporting: It does not display the E-STRICT, E-NOTICE and E_DEPRECATED level errors and display all the other level errors.display_errors: Its default value is "off". Set it to "on".log_errors: It's default value is "on" which indicates whether or not error logging should be
2 min read
How to display string values within a table using PHP ?
A table is an arrangement of data in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis. Tables are useful for various tasks such as presenting text information and numerical data.Tables can be used to compare two or more items in the tabular form layout.Tables are used to
1 min read
Write a program to display Reverse of any number in PHP ?
Write a program to reverse the digits of an integer. Examples : Input : num = 12345 Output: 54321 Input : num = 876 Output: 678 It can be achieved using Iterative way or Recursive Way Iterative Method: Algorithm: Input: num (1) Initialize rev_num = 0 (2) Loop while num &gt; 0 (a) Multiply rev_num by 10 and add remainder of num divide by 10 to rev_n
2 min read
How to display array structure and values in PHP ?
In this article, we will discuss how to display the array structure and values in PHP. To display the array structure and its values, we can use var_dump() and print_r() functions. It includes Array sizeArray valuesArray value with IndexEach value data type We will display the array structure using var_dump() function. This function is used to dump
2 min read
How to Display Days in a Grid by Weeks in PHP?
Displaying days in a grid by weeks consists of iterating over each day within a specified time range, organizing them into rows representing weeks and columns representing days of the week. Below are the approaches to display dates in a grid by weeks in PHP: Table of Content Using strtotime function Using DateTime objects and DateIntervalUsing strt
2 min read
How to display text with a PHP script ?
PHP allows us to display the text in various formats using various inbuilt methods. Table of Content Using echo commandUsing print command Using sprintf()Using var_dump()Using echo commandThe echo command can be used to display text, including numerical, strings and arrays. Example 1: [GFGTABS] PHP &lt;?php $string = &quot;GeeksforGeeks!!&quot;; //
3 min read
How to Display an Error for Invalid Input with PHP/HTML?
PHP can be easily embedded in HTML files, and HTML code can also be written in a PHP file. The key difference between PHP and a client-side language like HTML is that PHP code is executed on the server, while HTML code is directly rendered in the browser. To display errors for invalid input using HTML and PHP, follow this approach: Display an error
2 min read
How to display multiple recaptchas on a single page in PHP ?
RECAPTCHA is a free service from Google that helps to protect websites from spam and abuse. A “CAPTCHA” is a Turing test to tell humans and bots apart. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep malicious software from engaging in abusive activities on your website.  In this article, we are going to discuss how
5 min read
How to Display HTML Tags as Plain Text using PHP?
HTML tags begin with the less-than character and end with greater-than character, the text inside the tag formatted and presented according to the tag used. Every tag has special meaning to the browser but there are cases when to show plain HTML code in webpage. There are various methods in PHP to show the HTML tags as plain text, some of them are
3 min read
How to extract the user name from the email ID using PHP ?
Given a string email address, extract the username. Input: ‘priyank@geeks.com’ Output: priyank Input: ‘princepriyank@gfg.com’ Output: princepriyank Approach 1: Using PHP strstr() to extract the username from the email address. In this, “@” symbol is the separator for the domain name and user name of the email address. The strstr() PHP function is u
2 min read
How to validate and sanitize user input with PHP?
Data validation is an integral part of web development, especially while working with forms where the user first enters their personal data and then sends that to the database. Data sent in an invalid format can cause DBMS security problems. Hackers often use SQL injections to insert malicious SQL commands into the database. SQL injections can even
4 min read
How to take user input for two dimensional (2D) array in PHP ?
There are two methods to take user input in PHP in two dimensional (2D) array. Approach 1: Use HTML forms through PHP GET &amp; POST method to take user input in two dimensional (2D) array.First, input data into HTML forms.Then use the GET or POST method of PHP to get or post those input data into a variable.Finally, use that variable that holds in
3 min read
How the User-Defined Function differs from Built-in Function in PHP ?
In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions. User-Defined FunctionsUser-defined functions are functions created by
2 min read
How to read user or console input in PHP ?
In PHP, the console is a command-line interface, which is also called interactive shell. We can access it by typing the following command in a terminal: php -a If we type any PHP code in the shell and hit enter, it is executed directly and displays the output or shows the error messages in case of any error. A sample run of a PHP code, that reads i
4 min read
How to get user profile using Facebook SDK and PHP?
Facebook Graph APIs are used heavily among Facebook developers in the web or social networking world. These are totally HTTP-based protocols that help in getting or posting data, uploading photos, and videos, and sending group requests around social graphs. The Facebook SDK helps in providing wonderful features for enhancing user interfaces with Fa
3 min read
How to get the information from a meta tag using JavaScript ?
To display meta tag information in HTML with JavaScript, we will use a method called getElementByTagName() function. Method 1: Using getElementsByTagName() method. Syntax: document.getElementsByTagName("meta"); With this, we can get all the meta elements from an HTML file. As we click on the button, all the meta tag names and content will be displa
2 min read
How to define style information of a document using HTML5 ?
In this Article, we define style information for a document by using the &lt;style&gt; element in the document. It is used to change our text, viewed on the page. This change includes changing font-size, font-family, font-color, etc. Not only the texts but you can also change the style of a body or part of a page. Now let us look into various attri
1 min read
Article Tags :