Session
Use Zap's SessionManager to store encrypted values under named session entries,
read the configured session cookie name with config('app.session'), regenerate
the session ID after login, and clear state when logging out. The manager is registered as a
singleton, so controller actions share the same instance.
Resolve SessionManager
The application provider registers SessionManager as a singleton. Type-hint
it in a controller action and the router resolves it through the container; you do not
need to instantiate it manually.
use Zap\Core\Http\Response;
use Zap\Core\Utils\SessionManager;
public function dashboard(SessionManager $session): Response
{
if (!$session->has('user_id')) {
return $this->redirect(route('login'));
}
$userId = $session->get('user_id');
return $this->view('pages.dashboard', ['userId' => $userId]);
}
Outside a controller action, resolve the same singleton with the app()
helper. The application entry point starts the session before dispatching the request.
use Zap\Core\Utils\SessionManager;
$session = app(SessionManager::class);
// Safe to call again: start() only starts a session when none is active.
$session->start();
start() must run before response output. It throws when headers have already
been sent, and it configures the session cookie lifetime, garbage collection, and security
flags.
Session names and stored keys
Zap uses two different names. The PHP session cookie name comes from
config('app.session'), which reads the SESSION_NAME value from
your .env file and defaults to zap_session. The first argument
to set(), get(), has(), and unset()
is the name of the stored session entry, such as user.
use Zap\Core\Utils\SessionManager;
$session = app(SessionManager::class);
// The configured PHP session cookie name.
$cookieName = config('app.session'); // "zap_session" by default
// The name PHP is currently using for the session cookie.
$currentName = session_name();
// Store data under the "user" session entry.
$session->set('user', [
'id' => 7,
'name' => 'Alex',
]);
// Read the named entry back.
$user = $session->get('user', []);
config('app.session') is the session cookie name, not a data key. Calling
$session->set(config('app.session'), $value) would create a data entry
named zap_session; it would not rename the session cookie.
To apply the configured name, call session_name() before the session starts.
Do this in your entry point if you need the name to differ from PHP's default.
use Zap\Core\Utils\SessionManager;
session_name((string) config('app.session'));
$session = app(SessionManager::class);
$session->start();
session_start(). Changing it after the
session is active or after response output has begun will not rename the existing cookie.
Store, read, and update values
set($name, $value) stores or replaces an entire entry.
updateVal() merges fields into an array entry without removing the other
keys, and getVal() reads one field from that array.
$session->set('user_id', 42);
$session->set('user', [
'id' => 42,
'name' => 'Alex',
'role' => 'editor',
]);
$id = $session->get('user_id');
$user = $session->get('user', []);
$name = $session->getVal('user', 'name', 'Guest');
// Update a single field.
$session->updateVal('user', 'role', 'admin');
// Merge several fields at once.
$session->updateVal('user', [
'name' => 'Alex Doe',
'last_seen_at' => date('c'),
]);
if ($session->has('user')) {
// The entry exists and can be read with get() or getVal().
}
// Remove only the "user" entry.
$session->unset('user');
set()returnsvoid;has()returns a boolean.get($name, $default)returns the default when the entry is missing or its encrypted payload cannot be verified.getVal($name, $key, $default)works only when the stored value is an array.updateVal($name, $key, $value)updates one field; pass an array as the second argument to merge several fields.unset($name)removes one entry and returnstruewhen the operation completes.
$_SESSION.
Always read them through get() or getVal() instead of reading
$_SESSION directly.
Log in after credential verification
First validate the credentials against your user store. After successful authentication, regenerate the session ID and store only the identity or other necessary application state. The scalar entry below is convenient for a simple login check.
$session->regenerate();
$session->set('user_id', $verifiedUserId);
return $this->redirect(route('dashboard'));
For richer session state, group related fields under one named entry. Read individual
fields later with getVal().
$session->regenerate();
$session->set('user', [
'id' => $verifiedUserId,
'name' => $verifiedUserName,
'role' => $verifiedUserRole,
]);
return $this->redirect(route('dashboard'));
Security::get_instance()->validate_request(true)
as described in the Security guide.
Do not put passwords or raw credentials in the session.
Check session state
Use has() for a presence check and get() or
getVal() to retrieve the stored value. The default is returned when an entry
is missing or its encrypted payload cannot be decoded.
public function account(SessionManager $session): Response
{
if (!$session->has('user_id')) {
return $this->redirect(route('login'));
}
$userId = $session->get('user_id');
$displayName = $session->getVal('user', 'name', 'Guest');
return $this->view('pages.account', [
'userId' => $userId,
'displayName' => $displayName,
]);
}
For reusable route protection, put this check in your application's authentication middleware rather than duplicating it in every protected controller action.
Log out and clear session state
Make logout a state-changing POST or DELETE action, validate its CSRF token, then destroy
the session. destroy() clears all session data and expires the PHP session
cookie.
use Zap\Core\Utils\Security;
use Zap\Core\Utils\SessionManager;
public function logout(SessionManager $session): Response
{
if (!Security::get_instance()->validate_request(true)) {
return $this->text('Invalid CSRF token.', 403);
}
// The optional cookie name also expires that named cookie.
$session->destroy('remember_me');
return $this->redirect(route('login'));
}
Use unset('user_id') only when removing that one value is intended; use
destroy() to end the entire session and clear its cookie. Pass a cookie name
to destroy() when logout should also remove a related remember-me cookie.
Session security and configuration
SessionManager::set()encrypts values with AES-256-CBC and authenticates the ciphertext with HMAC-SHA256.- The session cookie name is exposed as
config('app.session'); setSESSION_NAMEin.envto change it. - Set a strong
APP_KEY(at least 32 characters); generate one withphp console generate --key. - Regenerate the session ID after login or privilege changes to reduce session-fixation risk.
start()sets a one-day cookie and garbage-collection lifetime, uses HttpOnly and SameSite=Lax, and enables Secure when HTTPS is detected.- Session and cookie encryption use the same application key; keep it secret and stable across deployments.
Validate CSRF tokens in each POST, PUT, PATCH, and DELETE action.