security
Session Security
Sessions connect a browser cookie to server-side authenticated state. Session security depends on cookie settings, ID regeneration, expiry, invalidation, and a backend that is reachable by every app server.
Core Controls
- Regenerate the session ID after login and privilege changes.
- Invalidate server-side session state on logout.
- Use HTTPS plus secure, HTTP-only, same-site cookies.
- Keep session data small and avoid storing fresh permission decisions indefinitely.
- Use shared session storage for load-balanced applications.
Configure The Session Cookie
Set cookie options before starting the session:
<?php
declare(strict_types=1);
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
echo 'Session cookie options prepared.' . PHP_EOL;
// Prints:
// Session cookie options prepared.
Production authentication sessions should travel over HTTPS. Use a deliberate local-development setup rather than weakening production flags.
Rotate And Invalidate State
Regenerate the ID after login and meaningful privilege changes. On logout, clear the server-side session, expire the browser cookie with the same scope, and revoke any remember-me token separately.
Define idle and absolute expiry rules. A user actively browsing may refresh the idle timeout, but a session should not remain valid forever.
Store Small Trusted References
Store a user ID and short-lived UI state, not a stale copy of every permission. Load current account status and permissions from trusted storage when the risk requires it.
In load-balanced systems, every application server must reach the same session backend unless routing deliberately pins one user to one server.
In Application Work
Review remember-me flows separately from normal sessions. Persistent login tokens need rotation, revocation, hashing at rest, and careful device management.
What To Check
Before moving on, make sure you can configure session-cookie flags, regenerate IDs, invalidate logout state, define expiry rules, and explain shared storage in a multi-server application.
Practice
Practice: Review A Login Session
Requirements
- Regenerate the ID after successful login.
- Store only necessary authenticated state.
- Set cookie security options.
- Define logout and idle-expiry behaviour.
Show solution
Review Points
- Regenerate the session ID after login and privilege changes.
- Invalidate server-side session state on logout.
- Use HTTPS plus secure, HTTP-only, same-site cookies.
- Keep session data small and avoid storing fresh permission decisions indefinitely.
- Use shared session storage for load-balanced applications.