Flash messages are one-time notifications stored in the session that survive exactly one redirect. They are ideal for displaying success or error feedback after a POST/Redirect/GET cycle.
PHP
Beginner
7 min read
Flash Messages
Example
<?php
session_start();
// ---- Helper functions ----
function flash(string $type, string $message): void
{
$_SESSION['_flash'][$type][] = $message;
}
function getFlash(string $type): array
{
$messages = $_SESSION['_flash'][$type] ?? [];
unset($_SESSION['_flash'][$type]); // consume (one-time)
return $messages;
}
function hasFlash(string $type): bool
{
return !empty($_SESSION['_flash'][$type]);
}
// ---- In your controller / handler ----
// After a successful save:
flash('success', 'Profile updated successfully!');
flash('success', 'Email notification sent.');
header('Location: /profile');
exit;
// ---- In your view (after redirect) ----
foreach (getFlash('success') as $msg) {
echo '<div class="alert alert-success">' . htmlspecialchars($msg) . '</div>';
}
foreach (getFlash('error') as $msg) {
echo '<div class="alert alert-danger">' . htmlspecialchars($msg) . '</div>';
}
Pro Tip
Tip: Flash messages are consumed the moment you read them — perfect for the PRG (Post/Redirect/Get) pattern. Store the messages before the redirect; retrieve and display them on the next page load, then they vanish automatically.