Session Middleware
What is Session Middleware?
Section titled “What is 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.
Components
Section titled “Components”A session middleware system consists of two parts:
-
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. -
SessionMiddleware (
app/Middleware/SessionMiddleware.php): a PSR-15 middleware class that callsSessionManager::start()on every request. Once registered globally inconfig/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.
SessionManager API Reference
Section titled “SessionManager API Reference”Once the middleware is registered, you can use the following SessionManager methods anywhere in your application:
| Method | Description |
|---|---|
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 dataSessionManager::set('user_id', 123);
// Retrieve data with a default value$userId = SessionManager::get('user_id', null);
// Check if a key existsif (SessionManager::has('user_id')) { // User is logged in}
// Remove a specific keySessionManager::remove('cart');
// Destroy session (e.g., on logout)SessionManager::destroy();