Creating Session based Flash Messages in PHP

Creating flash messages in PHP can be a dreadful task compared to doing it in a single page application with a Rest API. However, flash messages are extremely important for user experience and therefore it is worth implementing them in every PHP application. This tutorial will show you how to implement a session based flash messaging system with only PHP.

The idea

At the end of this tutorial, we will have a system that allows us to dynamically create and remove flash messages. The idea is to create a function that when called the first time puts a flash message into the $_SESSION superglobal and makes the message identifiable via a name (read more about this PHP superglobal here). When calling the method once more and passing the name of the flash message, the flash message will be displayed and the data will be removed from $_SESSION. That way, the message will only be displayed once. Don’t worry if that sounds confusing. You will realize that it’s actually not that difficult when you create it yourself.

Prerequisites

All you need is a PHP development environment running. I use XAMPP, but there are other apps like MAMP that work just as fine.

The flash messaging folder structure

We need three files for this:

flash.php
create_new_message.php
display_message.php

We will use flash.php to create our method for creating flash messages.
create_new_message.php will generate a new flash message every time we reload the page.
display_message.php will display the flash message and remove it afterwards

The flash method

The following code will be written in flash.php.

As indicated above, we will use sessions in our script. For this to work, we first have to start a session:

<?php
session_start();

You can find more information about sessions and starting sessions in particular here.

The function parameters

Our function will take three parameters: a name that identifies the flash message, an actual message that will be displayed to the user and a class name. The class name is important in order to enable flash messages of different sorts (e.g. green background for success or red background for errors).

<?php
session_start();

//added:
function flash($name = "", $message = "", $class = ")
{
}

As you can see we gave empty default values to each parameter. That way, our application won’t break if we call the function and pass less than three values. This becomes very important in the next part, where our function basically has to decide what it should do.

Deciding what to do when calling the function

This is the most important part. As stated above, we have to call the function two times in order to display the flash message. When calling it the first time, the message will be stored in the PHP supergloabl $_SESSION. When calling it the second time, the message should be displayed and the data should be removed from the session. But how do we tell the function when to do what? We accomplish this by playing around with the numbers of parameters we pass to the function when calling it.

Creating flash messages in PHP: Session storage

We define that when all the parameters are passed into the function, the flash method shall put the data into $_SESSION. Like so:

<?php
session_start();

function flash($name = "", $message = "", $class = ")
{
//added:
if (!empty($name) && !empty($message) && !empty($class)) {
            if (!empty($_SESSION[$name])) {
                unset($_SESSION[$name]);
            }
            if (!empty($_SESSION[$name . "_class"])) {
                unset($_SESSION[$name . "_class"]);
            }
            $_SESSION[$name] = $message;
            $_SESSION[$name . "_class"] = $class;
        }
}

First, the function checks if all three parameters are provided and only proceeds if this is the case. Secondly, it checks if there is already a key-value pair in $_SESSION that has the same key as $name passed into the function. If so, it unsets $[„name“]. It thirdly does the same with a key-value pair which has the key $key . „_class“. Finally, two key-value pairs are set in $_SESSION. The first takes $name as the key and $message as the value. The second one puts $name . „_class“ as the key and $class as the value.

It would have also been possible to not unset the session variables when they already exist. I decided to do so, however, in case that the message changes. For example, one might accidentally call flash() two times with all three parameters and the same $name variable. The way we set up our function, the stored message will be the second one. If you prefer to, you may of course not overwrite $_SESSION[„message“].

We now have everything we need in the $_SESSION superglobal in order to display session based flash messages in PHP applications.

Displaying the flash message

We now have everything available in the session, but we still need to display it to the user. We tell our flash() function to display the message by only passing the $name variable to it. Then, the function should execute the following code:

<?php
session_start();


function flash($name = "", $message = "", $class = "alert alert-success")
{
    if (!empty($name)) {
        if (!empty($name) && !empty($message)) {
            if (!empty($_SESSION[$name])) {
                unset($_SESSION[$name]);
            }
            if (!empty($_SESSION[$name . "_class"])) {
                unset($_SESSION[$name . "_class"]);
            }
            $_SESSION[$name] = $message;
            $_SESSION[$name . "_class"] = $class;
        } 
            //ADDED:
            elseif (empty($message) && empty($class) && !empty($name) && !empty($_SESSION[$name])) {
            echo '<div class="' . $_SESSION[$name . "_class"] . '" id="msg-flash">' . $_SESSION[$name] . '</div>';
            unset($_SESSION[$name]);
            unset($_SESSION[$name . "_class"]);
        }
    }
}

As you can see we now added the logic to what should happen if only the $name variable is passed into the function and there is a key-value pain in $_SESSION with the $name – key.

In that case, the function will echo a div with the classname that we stored under $_SESSION[$name . „_class“] and an inner text of the message string we stored under $_SESSION[$name]. You can essentially put everything here what you want. Whatever the style guidelines for your project are will be okay.

After echoing the div, the session variables are unset. This makes sure that when reloading the page, the alert will not pop up again.

Example

The heavy lifting is all done. We can now implement the function in the other two files. First, in create_new_message.php, do the following:

<?php
flash("my_first_flash_message, "This is my first flash message!", "alert");

When you open this file in the browser, the flash message fill start a session and modify $_SESSION the following way:

$_SESSION = [
    "my_first_flash_message"="This is my first flash message!",
    "my_first_flash_message_class" = "alert"
];

Next, we move to display_message.php:

<?php
flash("my_first_flash_message");

When the $_SESSION superglobal is set accordingly, the flash message will appear. When you then reload the page, the message won’t appear anymore. Just like we wanted it to.

Wrap-up

As you can see, creating flash messages in PHP based on sessions is not that difficult.
You can extend this in any way you want, of course. You could, for example, implement this flash messaging into your WordPress theme and modify it to your specific needs. If you want to know more about WordPress development, however, I suggest that you check out this series about plugin development.