Flash Messages Demo
Try It
Click a button to trigger a flash message. Notice:
- The message appears after the redirect
- Refresh the page - the message is gone!
- The URL stays clean (no query parameters)
Why flash messages?
After processing a form, you should redirect (Post-Redirect-Get pattern) to prevent duplicate submissions on refresh. But how do you show "Saved!" after the redirect?
Flash messages solve this by storing the message in the session temporarily.
The Pattern
<?php
session_start();
// Helper functions
function setFlash(string $type, string $message): void {
$_SESSION['flash'] = ['type' => $type, 'message' => $message];
}
function getFlash(): ?array {
$flash = $_SESSION['flash'] ?? null;
unset($_SESSION['flash']); // Delete immediately!
return $flash;
}
// In your form handler
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Process form...
saveDataToDatabase($_POST);
// Set flash message
setFlash('success', 'Your changes have been saved!');
// Redirect (Post-Redirect-Get)
header('Location: /dashboard');
exit;
}
// In your view
$flash = getFlash();
if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?>">
<?= htmlspecialchars($flash['message']) ?>
</div>
<?php endif; ?>
Why It Works
| Step | What Happens |
|---|---|
| 1. Form Submit | POST to server, data processed |
| 2. Set Flash | $_SESSION['flash'] = ['type' => 'success', 'message' => '...'] |
| 3. Redirect | Browser receives 302 redirect, makes new GET request |
| 4. Display | getFlash() reads message AND deletes it |
| 5. Refresh | Message is gone (was deleted in step 4) |