Mastering PHP Sessions: A Beginner’s Guide


Introduction

A website can provide incredibly powerful functionality, and if a developer wishes to provide that functionality to an individual user based on their actions, they will need to use PHP Sessions. Some common uses of a session involve logging a user in and storing items in a shopping cart. A session allows this information to be saved until the browser closes (generally speaking).

In this tutorial, we will create a session that allows a user to log in and store items in a shopping cart for checkout later, while also covering some beneficial security practices. Let’s jump into it!



1. Starting a PHP Session

First, create a .php file in your text editor of choice (some personal favorites are VS Code and Vim). Call it whatever you’d like. All PHP begins with: <?php and ends with ?>.

The first thing to write between these tags will be: session_start();. This will search your browser’s cookies to see if you already have a session available for your website. If this is the first time, session_start(); will create a new session via a cookie with a unique session ID.

Your program should look something like this:


<?php
// Start the session
session_start();
?>



2. Accessing Session Data

To access the stored session data, simply retrieve the information from the $_SESSION array. This can be done on any page where the session is active, as long as session_start() is called at the top. If we want to print a welcome message to our friend John, we could use the following code:


<?php
session_start();

// Store data in session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'john@example.com';

// Access session variables
echo 'Hello, ' . $_SESSION['username'];
?>

This will output:

Hello, JohnDoe

You can access any variable using $_SESSION['variableName']; This command is great for debugging. The period between 'Hello, ' and $_SESSION... is for string concatenation, combining “Hello, ” and “JohnDoe,” the username.



3. Modifying and Deleting Session Data

Sometimes, you may need to update or delete session data:

  • To modify session data, just assign a new value to the session variable:
    $_SESSION['username'] = 'JaneDoe';
  • To delete a specific session variable, use unset():
    unset($_SESSION['username']);


4. Destroying a PHP Session

To completely destroy a session and remove all session data, use session_destroy();. This is typically done when a user logs out of a website, ensuring no session data remains accessible after the user has logged out.

Your code might look like this:


<?php
session_start();

$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'john@example.com';

echo 'Hello, ' . $_SESSION['username'];

// Destroy the session
session_destroy();
?>

Note that session_destroy(); deletes the session data on the server but does not automatically remove the session cookie (PHPSESSID) from the user’s browser. To fully terminate the session, manually unset the session cookie:


<?php
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
}
session_destroy();
?>



5. Building a Simple Login System

Now that we understand how to start sessions and store data, let’s build a simple login system. Imagine we have a form where users enter their username and password. Once authenticated, we will store their information in the session.

For security reasons, you’ll want to retrieve these from a database. For a great tutorial on database creation, I recommend this video.


<?php
session_start();

// If the username is 'JohnDoe' and password is 'password123'...
if ($_POST['username'] == 'JohnDoe' && $_POST['password'] == 'password123') {
    // Save their username as a session variable...
    $_SESSION['username'] = $_POST['username'];
    // And print a welcome message with their username.
    echo 'Login successful. Welcome, ' . $_SESSION['username'] . '!';
} else {
    // Otherwise, display an invalid message.
    echo 'Invalid login credentials.';
}
?>



6. Adding Items to a Cart

Let’s add a feature where users can add items to their shopping list, and we will keep track of these items in a cart.


<?php
session_start();

// Check if the user is logged in
if (isset($_SESSION['username'])) {
    // Initialize the shopping list if not already set
    if (!isset($_SESSION['shopping_list'])) {
        // We create an empty ARRAY (a list).
        $_SESSION['shopping_list'] = [];
    }

    // Check if a book is sent via POST
    if (isset($_POST['book'])) {
        // Add the book to our shopping list
        $_SESSION['shopping_list'][] = $_POST['book'];
        // Print a message saying which book was added
        echo 'Book added: ' . $_POST['book'] . '
'; } } else { echo 'Please log in to add books to your shopping list.'; } ?>



7. Displaying the Shopping List

We can display the current shopping list by looping through each item in the $_SESSION['shopping_list'] array and printing it out.


<?php
session_start();

// Display the current shopping list
echo 'Your shopping list:<br>';
foreach ($_SESSION['shopping_list'] as $item) {
    echo '- ' . $item . '<br>';
}
?>



8. Destroying the Shopping Cart upon Checkout

Once the user is ready to check out, we will clear the shopping cart to simulate a checkout process.


<?php
session_start();

// Check if the user is logged in
if (isset($_SESSION['username'])) {
    // Clear the shopping list upon checkout
    if (isset($_POST['checkout'])) {
        unset($_SESSION['shopping_list']);
        echo 'Thank you for your purchase! Your shopping cart has been cleared.';
    }
} else {
    echo 'Please log in to check out.';
}
?>



9. Final Example

    All in all, our code makes a lot of assumptions. However, when all is said and done, it should look something like this:


<?php
// Start the session
session_start();

// Dummy authentication
if ($_POST['username'] == 'JohnDoe' && $_POST['password'] == 'password123') {
    $_SESSION['username'] = $_POST['username'];
    echo 'Login successful. Welcome, ' . $_SESSION['username'] . '!';
} else {
    echo 'Invalid login credentials.';
}

// Check if the user is logged in
if (isset($_SESSION['username'])) {
    // Initialize the shopping list if not already set
    if (!isset($_SESSION['shopping_list'])) {
        $_SESSION['shopping_list'] = [];
    }

    // Check if a book is sent via POST
    if (isset($_POST['book'])) {
        $_SESSION['shopping_list'][] = $_POST['book'];
        echo 'Book added: ' . $_POST['book'] . '<br>';
    }

    // Display the current shopping list
    echo 'Your shopping list:<br>';
    foreach ($_SESSION['shopping_list'] as $item) {
        echo '- ' . $item . '<br>';
    }

    // Clear the shopping list upon checkout
    if (isset($_POST['checkout'])) {
        unset($_SESSION['shopping_list']);
        echo 'Thank you for your purchase! Your shopping cart has been cleared.';
    }
} else {
    echo 'Please log in to add items to your shopping list or to check out.';
}

// Properly unset session cookie and destroy session
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() - 3600, '/');
}
session_destroy();
?>




References

  • W3Schools PHP Sessions: A great website that broadly explains what sessions are and how to use them. W3School’s interactive lessons are always a highlight of every tutorial they give. It covers the basics, including what a Session is, how to start, create, modify, and destroy session variables.
  • PHP Session Handling Guide by Kamal Bisht: If W3School is too simplistic, Kamal Bisht has a similar layout, but goes into much deeper explanations. The part about session security near the bottom is important. This comes right before suggestions on advanced implementation of session handling.
  • PHP Manual: Session Security: PHP’s official documentation on session security, including secure practices for cookies, secure mode, long-term vs short term storage, and more. This, and every post in the manual, is a great reference handbook for built-in functionality.
  • OWASP Session Management Cheat Sheet: The Open Web Application Security Project team provides fantastic resources for all things web security, and PHP is no exception. This is less of a PHP tutorial, and more guidelines for ensuring your web app is secure.
  • Dani Crossing’s PHP Tutorial on YouTube: A video covering how to create a database as part of a PHP tutorial, helpful for building secure login systems.


Discover more from Reagan Larsen

Subscribe to get the latest posts to your email.

Advertisements

Comments

Leave a comment