Once identity is established, the next question is:
how do we maintain it safely?
A session is a temporary identity.
It represents a user between requests
— nothing more, nothing less.
Security comes from treating the session as a boundary, not a convenience.
A session should be predictable, explicit, and difficult to misuse.
Modern PHP gives you the tools;
the discipline comes from how you use them.
This page introduces
the mental model for
safe session handling in PHP.
The most important rule is:
→ Regenerate the session ID immediately after authentication.
This prevents session fixation, where an attacker forces a victim to use a known session ID.
In PHP:
session_regenerate_id(true);
This creates a new session with a new ID and deletes the old one.
A session should never carry pre‑login identity into post‑login state.
The session cookie is the key to the user’s identity.
Protect it with strict boundaries:
In PHP:
session_set_cookie_params([ 'httponly' => true, 'secure' => true, 'samesite' => 'Strict', ]);
A session cookie should be treated like a password.
A session is not a storage container.
It is a state boundary.
Avoid storing:
Prefer storing:
Everything else should be fetched fresh
or cached elsewhere.
Small sessions are predictable sessions.
Do not store:
Sessions can be:
Treat the session as a place for identifiers, not secrets.
A proper logout:
In PHP:
$_SESSION = []; session_destroy(); setcookie(session_name(), '', time() - 3600);
Logout should be a boundary reset,
not a partial cleanup.
Long sessions increase risk.
Prefer:
A session should reflect active identity,
not historical identity.
Never use:
This exposes the session to:
Always use cookies for session identity.
A session is not a guarantee of identity
— it is a claim.
Validate:
A session should not outlive the truth of the system.
A session is not just a convenience.
It is a boundary between:
Security comes from respecting that boundary.
Secure session handling in PHP is about clarity and boundaries.
A secure system:
A session is temporary identity.
Treat it with care.
This page describes secure defaults and common practices in modern PHP. It is not a complete security guide, and it does not replace formal audits or framework‑specific documentation. These principles are consistent enough to be useful, but security always requires context, judgment, and ongoing review.