PHP 8 Intermediate HTTP & Files · 8 min read

PHP Sessions for a Signed-In User

Lesson 28 of 43 in the PHP 8 learning path.

How do I store a user id in $_SESSION safely?

The session stores data on the server and sends only the session id in a cookie. After session_start, $_SESSION is that data for the current visitor. On sign-in, store the user id as an integer and regenerate the session id so a fixation attack cannot keep an id the attacker chose. On sign-out, empty the array, expire the cookie, and call session_destroy.

Call session_start before any output. Set the cookie to HttpOnly and SameSite Lax, and mark it Secure on HTTPS, so script and cross-site posts cannot borrow it. Do not store a password, a password hash, or a permission dump you will forget to refresh. Load the user from the database with the id.

Syntax & Parameters

Syntax
$_SESSION = ['user_id' => $userId];

Example

public/cart.php
<?php

declare(strict_types=1);

ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');

if (PHP_SAPI === 'cli') {
    session_save_path(sys_get_temp_dir());
}

$https = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' && $_SERVER['HTTPS'] !== 'off';

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => $https,
    'httponly' => true,
    'samesite' => 'Lax',
]);

session_start();
session_regenerate_id(true);

$_SESSION = [
    'user_id' => 42,
];

$userId = $_SESSION['user_id'] ?? null;
if (! is_int($userId)) {
    throw new RuntimeException('The session user id must be an integer.');
}

$active = session_status() === PHP_SESSION_ACTIVE;

$_SESSION = [];
if (ini_get('session.use_cookies') === '1') {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', [
        'expires' => time() - 42000,
        'path' => $params['path'],
        'domain' => $params['domain'],
        'secure' => $params['secure'],
        'httponly' => $params['httponly'],
        'samesite' => (string) ($params['samesite'] ?? 'Lax'),
    ]);
}

session_destroy();

echo 'user ' . $userId . "\n";
echo 'active ' . ($active ? 'yes' : 'no') . "\n";
echo 'signed out' . "\n";
echo 'closed ' . (session_status() === PHP_SESSION_NONE ? 'yes' : 'no') . "\n";

Expected Output

user 42
active yes
signed out
closed yes

Line-by-Line Walkthrough

  1. The ini settings refuse a session id in the URL and reject an uninitialized id when strict mode is honored.
  2. A command-line run sets a temp save path. A web request keeps the server save path instead.
  3. The cookie is HttpOnly, SameSite Lax, and Secure only when HTTPS is on. These parameters are set before session_start.
  4. session_start loads the session. session_regenerate_id(true) issues a new id and deletes the previous session file.
  5. Replacing $_SESSION with user_id 42 drops any older keys, so a password cannot linger in the payload.
  6. The id is read back and rejected unless it is an integer.
  7. active records that the session was open before sign-out begins.
  8. Sign-out assigns an empty array, then expires the session cookie with the same path, domain, and flags.
  9. session_destroy removes the server data. All of this happens before any echo, so the cookie header can still be sent.
  10. The script then prints the user id, that the session was active, signed out, and that the status is now closed.

Common Pitfalls & Security

The cookie is only an identifier. Anyone who steals it can present that session until it expires or you destroy it. Protect the cookie and regenerate the id when the privilege changes.

  • Skipping session_regenerate_id on sign-in allows session fixation: the attacker sets the id, the victim signs in, and the attacker keeps the same id.
  • Storing a password, a hash, or a credit card number in $_SESSION copies a secret into the session store.
  • session.use_trans_sid can put the id in URLs, where it leaks through links and logs. Keep it off.
  • A Secure cookie on plain HTTP is dropped by the browser. Turn Secure on for HTTPS, not for an HTTP dev site that must keep the cookie.
  • Writing output before session_start or setcookie sends the body first, and the cookie header is lost.
  • Trusting a user_id hidden field after you have a session lets the client pick the account. Read the id from the session, then load the user.

Best Practices & Modern Standards

Store the smallest fact that lets you load the account: the integer user id. Regenerate the session id on sign-in and on any change of privilege. Set HttpOnly, SameSite Lax, and Secure on HTTPS. Use strict mode and cookies only.

On sign-out, empty $_SESSION, expire the cookie, and destroy the session. Load the user from the database on each request so a disabled account cannot keep acting on a stale session payload.

Real-World Use

Sign-in stores user id 42 and regenerates the session id. The cart page reads that integer and loads the account. Sign-out clears the session and expires the cookie. The password never enters $_SESSION.

Frequently Asked Questions

What should I store in the session?

The signed-in user id as an integer. Load the name, the role, and the cart from the database or from a short-lived cache keyed by that id.

Why regenerate the session id?

So an id created before sign-in cannot be reused by someone else after the password succeeds. Pass true to delete the old session file.

When do I call session_start?

Before any output, including a space or a warning. Call it once, then read and write $_SESSION.

How do I sign the user out?

Empty $_SESSION, expire the session cookie with the same flags, and call session_destroy. Do this before you print the next page.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…