Skip to content

The PHP Artisan

Have you written your next feature yet?

    • Write Ups
    • About Me

    How to use Session in PHP

    While developing or maintaining web applications, usually there’s a need of data persistence throughout the logic. Persistence means that if somewhere we get some kind of data, we want to store it for later. The most obvious and secure way to do this is to use a database. Databases provide the level of safety that the session will never be able to provide you and there’s a reason for that. Sessions are not secure nor can exist in the confines of a server for a large period of time.

    Sessions should not be used for storing extremely sensitive information such as passwords, bank information or personal user’s details. There’re used to control the flow of the web application and instruct the user what to do in terms of authorization and page access. Session are mainly developed as access guards to pages. Meaning that if you’re logged in before, as a user you may not want to log in again to access your dashboard. Web apps should be smart enough to recognize the user and navigate him/her accordingly.

    A session is essentially an block of memory that we can hold information in whatever format we deem fit and can be accessed throughout the web application for a limited period of time. Often used as a page guard to protect pages from public access.

    But how can we do that? Well, it’s quite simple. First of all you need to understand there are certain super globals in PHP. Super globals are those variables that have the ($_) prefix and usually are composed of capital letters. Some of them are $_SESSION, $_GET, $_POST, $_SERVER. As you can see, there are multiple super globals all made for a specific purpose. $_GET will hold the query parameters of a request, $_SERVER contains the server’s information and $_SESSION will hold whatever we instruct it to hold. Let’s first create a session. Suppose that the user entered the details onto the login page and the data was accepted and passed all the necessary validations.

    $user = array(
        'email' => 'artisan@php-artisan.com',
        'password' => '$@x29832e'
    );
    
    if (isset($user)) { 
        session_start();
        $_SESSION['user'] = $user;
        header('location: dashboard.php');
    } else {
        echo 'There has been an error.';
    }

    What do you need in order to use the Session

    First things first. Before we can use the super global to create a key value pair with our data, we need to use session_start(). This routine allows us to bring the super global forward so we can use it accordingly. It’s a good practice to include the session_start within the code block that you want to set up the session to avoid starting it without populating it. There’s a possibility that the condition will return false and we don’t want the session to be open without having any data in it. Once we set up the session, we usually want to redirect the user to the corresponding page of choice. We do this by using header()

    What if now the use closes the dashboard page and navigates the web for a period of time. In case the user returns we need to be able to know if has already logged in before so we can move him/her directly to the main page. We also need to make sure that no other user can access the corresponding URL without first logging into the application. What we need here is what we call a page guard. To create a page guard we just need to check for that $_SESSION['user'] record that we set up earlier on.

    session_start();
    if (!isset($_SESSION['user'])) {
        header('location: login.php');
    } else {
        $user_data = $_SESSION['user'];
    }
    
    echo 'Email: ' . $user_data['email'];

    If the key ‘user’ doesn’t exist in the $_SESSION super global, it means that either the session’s expired or the user’s not logged in. The moment the condition checks true, we redirect the user to the login page otherwise we create a variable to store the session data so we can display it on the page. But what happens when the user wants to log out? That’s the easiest case to account for. You only need to enable the session usage, destroy the session and then redirect the user to his/her mary way.

    session_start();
    session_destroy();
    header('location: home.php');

    Tags: $_GET$_POST$_SERVERhow to create a sessionhow to protect a page with sessionhow to use a sessionphpphp $_SESSIONphp functionsphp page guardphp sessionphp session loginsuper globals phpsuperglobals in php

    October 23, 2022 by administrator PHP

    You may also like...

    • How to Sort a Table by a MySQL Table Column

      How to Sort a Table by a MySQL Table Column

    • How to check if an array is empty in PHP?

      How to check if an array is empty in PHP?

    • Working with Files in PHP (The Brief Way)

      Working with Files in PHP (The Brief Way)

    • Next How to use include and require in PHP
    • Previous Difference between isset() and empty()

    Recent Entries

    • The Power of the Singleton Design Pattern: Creating Global Objects in PHP
    • CRUD Operations in PHP: A Beginner’s Guide
    • PHP OOP: Building Better Web Applications
    • Mastering MVC Design Pattern in PHP: A Complete Guide for Building Scalable and Maintainable Web Applications
    • How to Sort Arrays in PHP
    • How to Sort a Table by a MySQL Table Column
    • Working with Files in PHP (The Brief Way)
    • How to Submit a Form in PHP
    • Get JSON data from PHP file
    • What is a JS modal?
    • How to create a JSON Object in PHP?
    • How can I remove a specific item from an array?
    • How to check if an array is empty in PHP?
    • What does date() do in PHP?
    • What is a PHP class?
    • How does MVC pattern work?
    • What is stdClass in PHP?
    • Foreach in PHP
    • How to use include and require in PHP
    • How to use Session in PHP
    • Difference between isset() and empty()
    • Anonymous and Named Functions in PHP

    Categories

    • JavaScript
    • PHP

    The PHP Artisan © 2023. All Rights Reserved.

    Powered by WordPress. Theme by Alx.

      Manage Cookie Consent
      To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
      Functional Always active
      The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
      Preferences
      The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
      Statistics
      The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
      Marketing
      The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
      Manage options Manage services Manage vendors Read more about these purposes
      View preferences
      {title} {title} {title}