Development
How to Build Login With PHP Sessions

PHP session login works by verifying submitted credentials and storing the authenticated user's identifier in server-side session state. A protected route starts the session and checks that identity before returning private content.
The session is only one part of authentication. You also need HTTPS, password hashing, login throttling, CSRF protection for mutations, logout, expiry, and authorization for the requested resource.
Configure PHP sessions before output
For PHP 8.1 or newer, place the following bootstrap before any HTML. This configuration assumes HTTPS, including on your development environment when testing the Secure cookie.
<?php
declare(strict_types=1);
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
if (!session_start()) {
throw new RuntimeException('Session storage is unavailable.');
}
Strict mode helps reject uninitialized session identifiers, while HttpOnly reduces exposure to JavaScript access. SameSite is defense in depth and does not replace CSRF protection. PHP's session security guidance explains the relevant controls.
Verify a password hash and establish identity
Fetch a single user by the submitted identifier using a prepared database query. Store hashes generated with password_hash, never plaintext or a fast general-purpose hash. The following function assumes a validated account row and an already started session; it does not perform the database lookup.
<?php
/** Authenticate a retrieved account and replace the pre-login session. */
function establishLogin(array $user, string $password): bool
{
if (!isset($user['id'], $user['password_hash'])
|| !is_string($user['password_hash'])
|| !password_verify($password, $user['password_hash'])) {
return false;
}
if (!session_regenerate_id(true)) {
throw new RuntimeException('Could not rotate the session identifier.');
}
$_SESSION = [
'user_id' => (int) $user['id'],
'authenticated_at' => time(),
'last_seen_at' => time(),
'csrf' => bin2hex(random_bytes(32)),
];
return true;
}
Use a generic failed-login response whether the account is missing or the password is wrong. Account lookup, timing behavior, throttling, and disabled-account policy belong in the complete endpoint. See password_verify for hash verification behavior.
Regenerating the ID at authentication helps prevent session fixation. Concurrent requests can complicate immediate invalidation of an old session; test your session handler and application request pattern before choosing a rotation policy for a busy application.
Check authorization on every protected operation
A user_id proves only which identity the session represents. It does not prove that this user owns a particular invoice or can edit another user's account. Fetch resources within the authenticated user's permitted scope, and check administrative capabilities explicitly.
Enforce idle and absolute expiry using server-side timestamps. On expiry, remove authentication state and require login again. Do not rely on cookie lifetime or garbage collection timing to enforce the application's access policy.
For multiple application nodes, use an appropriate shared session handler and verify its locking and expiry behavior. Writing sessions to each node's local disk without routing or shared storage can produce intermittent logouts.
Complete logout and test the boundary
Logout should be a CSRF-protected POST. Clear session state, expire the cookie using its original path and flags, and destroy the server-side session. Make sensitive responses private and non-cacheable where appropriate.
Test successful and failed login, fixation attempts, session rotation, expired sessions, disabled accounts, cross-user resource access, and logout followed by a request using the old cookie. Browser back navigation must not reveal a usable authenticated operation after logout.
The example establishes a session boundary; production readiness depends on the surrounding endpoint and storage behavior. For the larger design, see incremental PHP refactoring or discuss an authentication review.