How to Create a Flash Message in PHP using Session Tutorial

In this tutorial, you will learn how to create a Flash Messages in PHP Language using PHP Session. The Flash Message that I am talking about is like the CodeIgniter's Flashdata Function. It allows the developer to store a temporary messages or data that can be access on the next request and after use.

How do Flash Messages Works?

The Flash Messages works something like the CodeIgniter's Flashdata Function where the developer can use it to store the process responses, error responses, messages, and other string data. This data will be stored using the PHP Session and when the data has called, the Flash Message stored in the session will b automatically removed.

Here, we will create a simple PHP application that has multiple buttons that triggers to save a Flash Message. After the successful saving of the flash message, the system will be redirected back to the page referrer and displays the message.

Getting Started

Download XAMPP as your local web server to run our PHP Script. After Installing the virtual server, open the XAMPP's Control Panel and start the Apache Server.

Download Bootstrap v5 for the interface design of the application that we'll be creating. After that move the library directory to the folder where you will store the source code on your end.

Creating The Interface

Below is the script of our Main Page which contains the elements codes for displaying flash messages and other displays. save this file as index.php.

  1. <?php require_once('function.php') ?>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4.  
  5. <head>
  6.     <meta charset="UTF-8">
  7.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9.     <title>Flash Messages</title>
  10.     <link rel="stylesheet" href="./Font-Awesome-master/css/all.min.css">
  11.     <link rel="stylesheet" href="./css/bootstrap.min.css">
  12.     <script src="./js/bootstrap.min.js"></script>
  13.     <style>
  14.         :root {
  15.             --bs-success-rgb: 71, 222, 152 !important;
  16.         }
  17.  
  18.         html,
  19.         body {
  20.             height: 100%;
  21.             width: 100%;
  22.             font-family: Apple Chancery, cursive;
  23.         }
  24.  
  25.         .btn-info.text-light:hover,
  26.         .btn-info.text-light:focus {
  27.             background: #000;
  28.         }
  29.     </style>
  30. </head>
  31.  
  32. <body class="bg-light">
  33.     <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
  34.         <div class="container">
  35.             <a class="navbar-brand" href="https://sourcecodester.com">
  36.             Sourcecodester
  37.             </a>
  38.  
  39.             <div>
  40.                 <b class="text-light">Flash Messages</b>
  41.             </div>
  42.         </div>
  43.     </nav>
  44.     <div class="container py-5" id="page-container">
  45.         <h4 class="text-center"><b>Flash Messages Like CodeIgniter's Flashdata Functions.</b></h4>
  46.  
  47.         <!-- Displaying Flash Data if exist -->
  48.         <?php if(isset($_SESSION['_flashdata'])): ?>
  49.             <!-- Looping All Flash messages -->
  50.             <?php foreach($_SESSION['_flashdata'] as $key => $val): ?>
  51.                 <div class="my-2 px-3 py2 alert alert-<?= $key ?>">
  52.                     <div class="d-flex align-items-center">
  53.                         <div class="col-11">
  54.                             <!-- Displaying the Flash Message -->
  55.                             <p><?= get_flashdata($key) ?></p>
  56.                         </div>
  57.                         <div class="col-1 text-end">
  58.                             <button class="btn-close" type="button" onclick="this.closest('.alert').remove()"></button>
  59.                         </div>
  60.                     </div>
  61.                 </div>
  62.             <?php endforeach; ?>
  63.             <!-- Looping All Flash messages -->
  64.         <?php endif; ?>
  65.         <!-- Displaying Flash Data if exist -->
  66.        
  67.  
  68.         <div class="col-lg-12 pt-5">
  69.             <div class="row">
  70.                 <div class="col-md-3 px-2">
  71.                     <a href="set_messages.php?msg=info" class="btn btn-lg rounded-pill btn-pill btn-info">Show an Info Message</a>
  72.                 </div>
  73.                 <div class="col-md-3 px-2">
  74.                     <a href="set_messages.php?msg=success" class="btn btn-lg rounded-pill btn-pill btn-success">Show a Success Message</a>
  75.                 </div>
  76.                 <div class="col-md-3 px-2">
  77.                     <a href="set_messages.php?msg=error" class="btn btn-lg rounded-pill btn-pill btn-danger">Show an Error Message</a>
  78.                 </div>
  79.                 <div class="col-md-3 px-2">
  80.                     <a href="set_messages.php?msg=multiple" class="btn btn-lg rounded-pill btn-pill btn-default border">Show a Multiple Message</a>
  81.                 </div>
  82.             </div>
  83.         </div>
  84.     </div>
  85.  
  86.  
  87. </body>
  88.  
  89. </html>

Creating The Main Function

Next, we will be creating the PHP file that contains the function of storing the flash messages, getting the data, and deleting the flash message. Save this file as function.php.

  1. <?php
  2. if(session_status() === PHP_SESSION_NONE)
  3.  
  4.  
  5. // Sets a flash message data function
  6. function set_flashdata($key = "", $value = ""){
  7.     if(!empty($key) && !empty($value)){
  8.         $_SESSION['_flashdata'][$key] = $value;
  9.         return true;
  10.     }
  11.     return false;
  12. }
  13.  
  14. // Getting the flashdata
  15. function get_flashdata($key=""){
  16.     if(!empty($key) && isset($_SESSION['_flashdata'][$key])){
  17.         $data = $_SESSION['_flashdata'][$key];
  18.         unset($_SESSION['_flashdata'][$key]);
  19.         return $data;
  20.     }else{
  21.         echo "<script> alert(' Flash Message \'{$key}\' is not defined. ')</script>";
  22.     }
  23. }

Creating the Process File

The script below is the code is the sample PHP File that stores the flash messages and redirects to the Main Page. Save this file as set_messages.php.

  1. <?php require_once('function.php') ?>
  2. <?php
  3. if(!isset($_GET['msg'])){
  4.     echo "<script> alert('No message to set.'); location.href='./'</script>";
  5. }
  6.  
  7. $msg  = $_GET['msg'];
  8.  
  9. switch ($msg){
  10.     case 'info';
  11.         set_flashdata('info',"<i class='fa fa-info-circle'></i> This is a Sample Info Message.");
  12.     break;
  13.     case 'success';
  14.         set_flashdata('success',"<i class='fa fa-check'></i> This is a Sample Success Message.");
  15.     break;
  16.     case 'error';
  17.         set_flashdata('danger',"<i class='fa fa-exclamation-triangle'></i> This is a Sample Error Message.");
  18.     break;
  19.     case 'multiple';
  20.         set_flashdata('info',"<i class='fa fa-info-circle'></i> This is a Sample Info Message.");
  21.         set_flashdata('success',"<i class='fa fa-check'></i> This is a Sample Success Message.");
  22.         set_flashdata('danger',"<i class='fa fa-exclamation-triangle'></i> This is a Sample Error Message.");
  23.     break;
  24.     default:
  25.         set_flashdata('danger',"Undefined Flash Message.");
  26.     break;
  27. }
  28. header('location:./');

And here's the sample snapshot of the application.

Result Image

DEMO VIDEO

That's it! You can now test the application in your browser and see if we have met our goal on this tutorial. If ever you have encountered any errors, please review your source code by differentiating it from the source code I provided above. You can also test the working source code I created for this tutorial. You can download the source code zip file below this article.

That is the end of this tutorial. I hope you'll find this Flash Messages in PHP Tutorial useful for your current and future projects.

Happy Coding :)

Add new comment