PHP sessions: Sign in, sign out, and protect a members-only page
To sign a user in with PHP, verify their password, rotate the session ID, and save the user ID in $_SESSION. The members page checks the server-side session and its expiry before sending content. Signing out clears the server session and cookie.
Set up the local files
With PHP 8.x, create a login-demo folder and save the files in the layout shown below. Use UTF-8 without a BOM and serve only public. Keep the account file and session data in app. The loopback-only demo uses the public account demo and sample password sample-only passphrase 42.
login-demo/
create-demo-user.php
app/
bootstrap.php
demo-user.php
sessions/
public/
login.php
content.php
logout.php
Create the demo account hash
Run create-demo-user.php from the command line. It hashes the sample password, creates app/demo-user.php, and refuses to overwrite an existing file. See the password hash generation and storage examples for hash generation and storage.
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit('Run this from the command line.');
}
$dir = __DIR__ . '/app';
if (!is_dir($dir) && !mkdir($dir, 0700, true)) {
throw new RuntimeException('Could not create the app directory.');
}
$record = [
'id' => 'demo',
'username' => 'demo',
'password_hash' => password_hash('sample-only passphrase 42', PASSWORD_DEFAULT),
];
$source = "<?php\nreturn " . var_export($record, true) . ";\n";
$file = fopen($dir . '/demo-user.php', 'x');
if ($file === false) {
throw new RuntimeException('The account file exists or could not be created. It was not overwritten.');
}
$written = fwrite($file, $source);
fclose($file);
if ($written !== strlen($source)) {
throw new RuntimeException('Could not finish writing the account file.');
}
echo 'The demo account file was created.', PHP_EOL;
Configure sessions and expiration
app/bootstrap.php sets cookie-only sessions and strict mode. The local HTTP cookie uses HttpOnly and SameSite=Lax. The server expires the demo after one hour from sign-in or 15 minutes of inactivity. In production, configure HTTPS, Secure cookies, and session storage for the deployment. PHP Manual · Session Security PHP Manual · Session Management
<?php
declare(strict_types=1);
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true)) {
http_response_code(403);
exit('This exercise runs locally only.');
}
$sessionDir = __DIR__ . '/sessions';
if (!is_dir($sessionDir) && !mkdir($sessionDir, 0700, true)) {
http_response_code(500);
exit('Could not prepare session storage.');
}
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
session_save_path($sessionDir);
session_name('CFLOGINDEMO');
session_set_cookie_params([
'lifetime' => 0, 'path' => '/', 'domain' => '', 'secure' => false,
'httponly' => true, 'samesite' => 'Lax',
]);
if (!session_start()) {
http_response_code(500);
exit('Could not start the session.');
}
header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-store');
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function csrfToken(): string {
if (!isset($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf'];
}
function validCsrf(mixed $token): bool {
return is_string($token) && hash_equals(csrfToken(), $token);
}
function redirectTo(string $path): void {
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
header('Location: ' . $path, true, 303);
exit;
}
function isLoggedIn(): bool {
if (($_SESSION['user_id'] ?? null) !== 'demo') {
return false;
}
$created = $_SESSION['logged_in_at'] ?? null;
$lastSeen = $_SESSION['last_seen'] ?? null;
$now = time();
if (!is_int($created) || !is_int($lastSeen)
|| $now - $created >= 3600 || $now - $lastSeen >= 900) {
unset($_SESSION['user_id'], $_SESSION['logged_in_at'], $_SESSION['last_seen']);
$_SESSION['csrf'] = bin2hex(random_bytes(32));
return false;
}
$_SESSION['last_seen'] = $now;
return true;
}
The sign-in and sign-out POST requests check the current session’s token to prevent cross-site request forgery (CSRF). Redirects use fixed local paths and exit after sending HTTP 303. OWASP · CSRF Prevention the PHP redirect example
Verify the password, then change the session ID
In public/login.php, GET displays the form and POST validates the token and input. A wrong username or password returns the same message. The password’s spaces are preserved. The 72-byte limit is this demo’s bcrypt compatibility rule. the password_verify() examples
<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (isLoggedIn()) {
redirectTo('/content.php');
}
$error = '';
$username = '';
$method = $_SERVER['REQUEST_METHOD'] ?? '';
if ($method === 'POST') {
if (!validCsrf($_POST['csrf'] ?? null)) {
http_response_code(403);
exit('Open the form again.');
}
$rawUser = $_POST['username'] ?? null;
$password = $_POST['password'] ?? null;
if (!is_string($rawUser) || !is_string($password)
|| strlen($rawUser) > 80 || strlen($password) > 72
|| $password === '' || str_contains($password, "\0")) {
http_response_code(422);
$error = 'Check the input format and length.';
} else {
$username = trim($rawUser);
$accountFile = __DIR__ . '/../app/demo-user.php';
if (!is_readable($accountFile)) {
http_response_code(500);
exit('Could not complete sign-in.');
}
$user = require $accountFile;
$passwordOK = password_verify($password, $user['password_hash']);
if ($username !== $user['username'] || !$passwordOK) {
http_response_code(401);
$error = 'The username or password is incorrect.';
} else {
if (!session_regenerate_id(false)) {
http_response_code(500);
exit('Could not complete sign-in.');
}
$now = time();
$_SESSION = [
'user_id' => $user['id'], 'logged_in_at' => $now,
'last_seen' => $now, 'csrf' => bin2hex(random_bytes(32)),
];
redirectTo('/content.php');
}
}
} elseif ($method !== 'GET') {
http_response_code(405);
header('Allow: GET, POST');
exit;
}
$csrf = csrfToken();
session_write_close();
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Local sign-in demo</title></head>
<body>
<h1>Sign-in demo</h1>
<?php if ($error !== ''): ?><p><?= e($error) ?></p><?php endif; ?>
<form method="post" action="/login.php">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<p><label>Username <input name="username" value="<?= e($username) ?>" autocomplete="username" required></label></p>
<p><label>Password <input type="password" name="password" autocomplete="current-password" required></label></p>
<button>Sign in</button>
</form>
<p><a href="/content.php">Check access to members-only content</a></p>
</body>
</html>
After verification, session_regenerate_id(false) changes the ID before the new session receives authentication state. The previous anonymous data is left temporarily without authentication. Design ID rotation and retirement separately for production traffic with concurrent requests. PHP Manual · session_regenerate_id()
Protect the members page on the server
public/content.php calls isLoggedIn() first. An unauthenticated or expired session goes to sign-in and receives no members-only content. The server deadline applies even if the browser still has a cookie.
<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (!isLoggedIn()) {
redirectTo('/login.php');
}
$userId = $_SESSION['user_id'];
$csrf = csrfToken();
session_write_close();
?>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Members-only demo</title></head>
<body>
<h1>Members-only content</h1>
<p>You are signed in as <?= e($userId) ?>.</p>
<p>This is sample members-only content.</p>
<form method="post" action="/logout.php">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<button>Sign out</button>
</form>
</body>
</html>
Sign out with POST and clear the cookie
public/logout.php returns 405 for GET and 403 for POST without a valid token. An accepted POST clears the session array and deletes the server data. The cookie is expired with its matching name, path, and domain before redirecting to sign-in. PHP Manual · session_destroy()
<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/bootstrap.php';
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
header('Allow: POST');
exit('Use the sign-out button.');
}
if (!validCsrf($_POST['csrf'] ?? null)) {
http_response_code(403);
exit('Open the form again.');
}
$name = session_name();
$params = session_get_cookie_params();
$_SESSION = [];
if (!session_destroy()) {
http_response_code(500);
exit('Could not complete sign-out.');
}
setcookie($name, '', [
'expires' => time() - 3600, 'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'], 'httponly' => $params['httponly'],
'samesite' => $params['samesite'],
]);
header('Location: /login.php', true, 303);
exit;
Run the demo and check the results
Run these two commands from the project folder in order. The server listens on 127.0.0.1 only. If port 8000 is busy, use the same alternative in the command and URL. Stop with Ctrl+C. If the session does not persist, check the URL, cookie transmission, and write access to app/sessions.
php create-demo-user.php
php -S 127.0.0.1:8000 -t public
- Open http://127.0.0.1:8000/content.php first. Expect the sign-in form with no members-only sentence.
- Submit a wrong password. The generic error appears and the protected page stays inaccessible.
- Sign in as demo with the public sample password. The members page remains available after a reload. A separate browser profile still requires login.
- Use the sign-out button and reopen content.php. The sign-in form should return and the protected sentence should be absent.
Plan authentication and authorization for production
For production, start with a vetted authentication component. Plan account status, per-resource authorization, attempt limits, multifactor authentication, recovery, and session invalidation. Cache-Control: no-store controls response caching. The server still makes the access decision at every protected route. OWASP · Authentication OWASP · Session Management




