Summary: in this tutorial, you’ll learn about the PHP flash messages and define a reusable flash()
function to manage the flash messages effectively.
Introduction to the PHP flash messages
A flash message allows you to create a message on one page and display it once on another page. To transfer a message from one page to another, you use the $_SESSION
superglobal variable.
For example, you can add a message to the $_SESSION
on the first page:
<?php
session_start();
$_SESSION['flash_message'] = "I'm a flash message';
Code language: PHP (php)
Later, on another page, you can get the flash message from the $_SESSION
variable and assign it to a variable. Then, you delete the message from the $_SESSION
and display the message:
<?php
session_start();
if(isset($_SESSION['flash_message'])) {
$message = $_SESSION['flash_message'];
unset($_SESSION['flash_message']);
echo $message;
}
Code language: PHP (php)
This is a simple flash message example.
In practice, a flash message has a name (or an ID) for reference later. Also, a flash message has a type such as error, success, information, and warning. The message type allows you to make a specific style for the message
In the following section, we’ll define a set of functions that do the following:
- Create a flash message with a name.
- Format a flash message.
- Display a flash message specified by a name.
- Display all the flash messages.
Create a flash message
First, define a constant as a key for all the flash messages:
const FLASH = 'FLASH_MESSAGES';
Code language: PHP (php)
Second, define constants that define the type of flash messages including error, information, warning, and success:
const FLASH_ERROR = 'error';
const FLASH_WARNING = 'warning';
const FLASH_INFO = 'info';
const FLASH_SUCCESS = 'success';
Code language: PHP (php)
Third, define a function that creates a flash message which has a name, a message, and a type:
<?php
/**
* Create a flash message
*
* @param string $name
* @param string $message
* @param string $type
* @return void
*/
function create_flash_message(string $name, string $message, string $type): void
{
// remove existing message with the name
if (isset($_SESSION[FLASH][$name])) {
unset($_SESSION[FLASH][$name]);
}
// add the message to the session
$_SESSION[FLASH][$name] = ['message' => $message, 'type' => $type];
}
Code language: PHP (php)
Format a flash message
The following format_flash_message()
function formats a flash message:
/**
* Format a flash message
*
* @param array $flash_message
* @return string
*/
function format_flash_message(array $flash_message): string
{
return sprintf('<div class="alert alert-%s">%s</div>',
$flash_message['type'],
$flash_message['message']
);
}
Code language: PHP (php)
In this function, we use the following HTML with the class alert
and alert-$type
to format the message. The message type can be an error, info, warning, and success.
The following example shows an error message:
<div class="alert alert-error">
This is an error!
</div>
Code language: HTML, XML (xml)
Display a flash message
To display a flash message by a name, you check if the message name exists in the $_SESSION[FLASH]
variable. If so, you get the flash message in the $_SESSION['FLASH']
, remove it from the $_SESSION['FLASH']
, and display the flash message:
<?php
/**
* Display a flash message
*
* @param string $name
* @return void
*/
function display_flash_message(string $name): void
{
if (!isset($_SESSION[FLASH][$name])) {
return;
}
// get message from the session
$flash_message = $_SESSION[FLASH][$name];
// delete the flash message
unset($_SESSION[FLASH][$name]);
// display the flash message
echo format_flash_message($flash_message);
}
Code language: PHP (php)
Display all flash messages
The following function displays all flash messages from the $_SESSION['FLASH']
variable:
<?php
/**
* Display all flash messages
*
* @return void
*/
function display_all_flash_messages(): void
{
if (!isset($_SESSION[FLASH])) {
return;
}
// get flash messages
$flash_messages = $_SESSION[FLASH];
// remove all the flash messages
unset($_SESSION[FLASH]);
// show all flash messages
foreach ($flash_messages as $flash_message) {
echo format_flash_message($flash_message);
}
}
Code language: PHP (php)
Define the flash() function
It would be more convenient if we define a single flash()
function that:
- Create a flash message
- Display a flash message
- Display all flash messages
The following flash()
function reuses the above functions:
<?php
/**
* Flash a message
*
* @param string $name
* @param string $message
* @param string $type (error, warning, info, success)
* @return void
*/
function flash(string $name = '', string $message = '', string $type = ''): void
{
if ($name !== '' && $message !== '' && $type !== '') {
create_flash_message($name, $message, $type);
} elseif ($name !== '' && $message === '' && $type === '') {
display_flash_message($name);
} elseif ($name === '' && $message === '' && $type === '') {
display_all_flash_messages();
}
}
Code language: PHP (php)
To create a flash message, you pass three arguments: name
, message
, and type
to the flash()
function like this:
flash('greeting', 'Hi there', FLASH_INFO);
Code language: PHP (php)
To display a flash message by a name
, you need to pass a name
to the flash()
function:
flash('greeting');
Code language: PHP (php)
To display all flash messages, you don’t pass any arguments to the flash()
function:
flash();
Code language: PHP (php)
Put it all together
The following places all the functions in the flash.php file:
<?php
const FLASH = 'FLASH_MESSAGES';
const FLASH_ERROR = 'error';
const FLASH_WARNING = 'warning';
const FLASH_INFO = 'info';
const FLASH_SUCCESS = 'success';
/**
* Create a flash message
*
* @param string $name
* @param string $message
* @param string $type
* @return void
*/
function create_flash_message(string $name, string $message, string $type): void
{
// remove existing message with the name
if (isset($_SESSION[FLASH][$name])) {
unset($_SESSION[FLASH][$name]);
}
// add the message to the session
$_SESSION[FLASH][$name] = ['message' => $message, 'type' => $type];
}
/**
* Format a flash message
*
* @param array $flash_message
* @return string
*/
function format_flash_message(array $flash_message): string
{
return sprintf('<div class="alert alert-%s">%s</div>',
$flash_message['type'],
$flash_message['message']
);
}
/**
* Display a flash message
*
* @param string $name
* @return void
*/
function display_flash_message(string $name): void
{
if (!isset($_SESSION[FLASH][$name])) {
return;
}
// get message from the session
$flash_message = $_SESSION[FLASH][$name];
// delete the flash message
unset($_SESSION[FLASH][$name]);
// display the flash message
echo format_flash_message($flash_message);
}
/**
* Display all flash messages
*
* @return void
*/
function display_all_flash_messages(): void
{
if (!isset($_SESSION[FLASH])) {
return;
}
// get flash messages
$flash_messages = $_SESSION[FLASH];
// remove all the flash messages
unset($_SESSION[FLASH]);
// show all flash messages
foreach ($flash_messages as $flash_message) {
echo format_flash_message($flash_message);
}
}
/**
* Flash a message
*
* @param string $name
* @param string $message
* @param string $type (error, warning, info, success)
* @return void
*/
function flash(string $name = '', string $message = '', string $type = ''): void
{
if ($name !== '' && $message !== '' && $type !== '') {
// create a flash message
create_flash_message($name, $message, $type);
} elseif ($name !== '' && $message === '' && $type === '') {
// display a flash message
display_flash_message($name);
} elseif ($name === '' && $message === '' && $type === '') {
// display all flash message
display_all_flash_messages();
}
}
Code language: HTML, XML (xml)
A flash message example
First, create the following directory and file structure:
├── inc
| ├── flash.php
| ├── footer.php
| └── header.php
├── page1.php
└── page2.php
Code language: plaintext (plaintext)
Second, place all the functions above in the flash.php
file.
Third, add the following code to the header.php
file. The header.php
links to the style.css
file in the css
folder:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://www.phptutorial.net/app/css/style.css">
<title>PHP Flash Message</title>
</head>
<body>
Code language: HTML, XML (xml)
Fourth, add the following HTML to the footer.php
file:
</body>
</html>
Code language: HTML, XML (xml)
Fifth, create a flash message on the page1.php
file by calling the flash()
function:
<?php
session_start();
require __DIR__ . '/inc/flash.php';
require __DIR__ . '/inc/header.php';
flash('greeting', 'Hi there', FLASH_INFO);
echo '<a href="page2.php" title="Go To Page 2">Go To Page 2</a>';
require __DIR__ . '/inc/footer.php';
Code language: PHP (php)
The page1.php
file has a link to the page2.php
.
Finally, show the greeting message on the page2.php
file by calling the flash()
function and pass the name into it:
<?php
session_start();
require __DIR__ . '/inc/flash.php';
require __DIR__ . '/inc/header.php';
flash('greeting');
require __DIR__ . '/inc/footer.php';
Code language: PHP (php)
If you open the page1.php
page and click the link, you’ll see a message on the page2.php
page.
PHP flash message use cases
In practice, you’ll use the flash messages on a signup page to redirect users to the login page with a welcome message after they sign up. Also, you’ll use the flash messages in the Post-Redirect-Get pattern, which you’ll learn in the next tutorial.
Summary
- A flash message is created on a page and displayed once on another page.
- Use the
$_SESSION
superglobal variable to manage the flash messages. - Use the
flash()
developed in this tutorial to manage flash messages.