Skip to content

Sessions and CSRF

Laureano F. Lamonega edited this page Jul 17, 2026 · 1 revision

Sessions & CSRF

Sessions and CSRF protection are opt-in — the framework does not start a session for you.

Enabling Sessions

In app/Config/app.php:

return [
    'timezone' => env('APP_TIMEZONE', 'UTC'),
    'session'  => true,
];

Session API

use Antimonial\Session\Session;

Session::put('user_id', 42);
$id = Session::get('user_id');       // 42
$id = Session::pull('user_id');      // 42, then removed
Session::has('user_id');             // bool
Session::forget('user_id');          // Remove single key
Session::forget(['key1', 'key2']);   // Remove multiple keys
Session::flush();                    // Clear all

// Flash data (available on the next request only)
Session::flash('status', 'Saved!');
$status = Session::getFlash('status');

// Regenerate session ID (call after login)
Session::regenerate();
Session::regenerate(true);  // Destroy old session data

// Session ID
$id = Session::id();

CSRF Protection

Token Generation

Render the CSRF token in forms using the @csrf directive:

<form method="post">
    @csrf
    <input name="name" value="">
</form>

Or manually:

use Antimonial\Security\Csrf;

$token = Csrf::token();
$html  = Csrf::field();  // '<input type="hidden" name="_token" value="...">'

CSRF Middleware

The framework includes CsrfMiddleware that verifies tokens on POST/PUT/DELETE/PATCH requests. Register it globally:

$router->addMiddleware(Antimonial\Middleware\CsrfMiddleware::class);

Or on a group:

$router->group('/admin', function (Router $r) {
    // routes here
}, [CsrfMiddleware::class]);

The middleware uses timing-safe comparison (hash_equals) and returns a 419 status on mismatch. Safe methods (GET, HEAD, OPTIONS) pass through.

Clone this wiki locally