Skip to content

Session Middleware

  • Session middleware automatically starts PHP sessions for your entire application.
  • Instead of calling session_start() in every route, the middleware handles it once before any route executes.
  • This ensures sessions are always available, eliminates the risk of forgetting to start them, and prevents errors from starting sessions multiple times.

A session middleware system consists of two parts:

  1. SessionManager (app/Helpers/SessionManager.php): a helper class that configures session security settings (cookie parameters, garbage collection, session ID regeneration, browser fingerprinting) and provides convenient static methods for working with session data.

  2. SessionMiddleware (app/Middleware/SessionMiddleware.php): a PSR-15 middleware class that calls SessionManager::start() on every request. Once registered globally in config/middleware.php, sessions are available in all controllers and routes without any manual setup.

You will implement both of these in the Session Middleware lab.


Once the middleware is registered, you can use the following SessionManager methods anywhere in your application:

MethodDescription
set($key, $value)Store data in the session
get($key, $default)Retrieve data from the session (returns default if key doesn’t exist)
has($key)Check if a key exists in the session
remove($key)Remove a specific key from the session
clear()Clear all session data (keeps session alive)
destroy()Destroy the session completely

Usage example:

use App\Helpers\SessionManager;
// Store data
SessionManager::set('user_id', 123);
// Retrieve data with a default value
$userId = SessionManager::get('user_id', null);
// Check if a key exists
if (SessionManager::has('user_id')) {
// User is logged in
}
// Remove a specific key
SessionManager::remove('cart');
// Destroy session (e.g., on logout)
SessionManager::destroy();