Harden sessions

A session id is a password that the browser sends on every request, so the cookie that carries it deserves the same care as a login. The examples below are pages of PHP served by php -S 127.0.0.1:8000 and requested with a client that keeps its cookie, which is the only way to see an id change. Background in PHP sessions.

Cookie params

The session id travels in a cookie, so lock that cookie down first. Set HttpOnly to hide it from scripts and restrict it to secure connections on live sites, which means HTTPS.

Call session_set_cookie_params() before session_start(). Every request that uses sessions needs the same call.

The file cookie.php in the folder you serve with php -S 127.0.0.1:8000:

<?php session_set_cookie_params([ "lifetime" => 0, "httponly" => true, ]); session_start(); echo "ready", PHP_EOL; echo session_name(), PHP_EOL;

curl -s "http://127.0.0.1:8000/cookie.php"

ready
PHPSESSID

The response carries Set-Cookie: PHPSESSID=...; path=/; HttpOnly, so a JavaScript script on the page cannot read the id, and that header is the same one setcookie() writes for a cookie of your own. The name comes from PHP itself and is the same on every request of this site.

Regenerate ids

Change the session id at privilege boundaries such as login and password change. The stored data stays, only the id changes.

Pass true to delete the old session record on the server. The old id stops working right away.

The file regen.php in the same folder:

<?php session_start(); $before = session_id(); $_SESSION["user_id"] = 42; session_regenerate_id(true); $after = session_id(); echo $before === $after ? "same id" : "new id", PHP_EOL; echo $_SESSION["user_id"], PHP_EOL;

curl -s "http://127.0.0.1:8000/regen.php"

new id
42

The two lines are the whole promise of the function: the id changed and the value stayed. A browser that held the old cookie now presents an id the server does not know.

Detect theft simply

A basic check compares a stored browser marker with the current request. If the marker changes, treat the session as suspect and clear it.

This is not perfect, but it stops casual id reuse. Keep the logic simple and log suspicious resets for review.

The file agent.php in the same folder:

<?php session_start(); $agent = $_SERVER["HTTP_USER_AGENT"] ?? ""; if (!isset($_SESSION["agent"])) { $_SESSION["agent"] = $agent; } if ($_SESSION["agent"] !== $agent) { $_SESSION = []; echo "reset", PHP_EOL; } else { echo "same browser", PHP_EOL; }

curl -s -A "Mozilla/5.0" "http://127.0.0.1:8000/agent.php"

same browser

The first request stores the marker and passes the check. A second request that sends the same cookie with another User-Agent prints reset and empties the session, which was checked with the same client and a different agent string.

Where sessions live

By default PHP stores session data in files on the server. Only the random id goes to the browser, never the data itself.

Use session_save_path to inspect the storage directory. On shared hosting keep that directory outside public web access.

The file where.php in the same folder:

<?php session_start(); echo session_save_path() === "" ? "php.ini default folder" : "custom folder", PHP_EOL; echo session_status() === PHP_SESSION_ACTIVE ? "session active" : "no session", PHP_EOL;

curl -s "http://127.0.0.1:8000/where.php"

php.ini default folder
session active

An empty save path means the folder comes from the configuration, which is the usual arrangement. The status line proves that the session is open, so the id in the response belongs to a stored record.

Exercises

  1. Add "samesite" => "Lax" and "secure" => true to the cookie params and read the Set-Cookie header of the response.
  2. Call session_set_cookie_params() after the first echo and read the warning the server writes.
  3. Store the user id before session_regenerate_id() and print it after, as the regen example does.
  4. Send two requests to the agent page with different User-Agent strings and keep the cookie in between.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call must come before session_start() to lock the session cookie down?

    Answer

    session_set_cookie_params()

    The parameters are read when the session starts, so the call has to happen first.

  2. Which flag keeps JavaScript from reading the session cookie?

    Answer

    httponly

    HttpOnly hides the cookie from document.cookie; Secure only limits it to HTTPS requests.

  3. Why is the id regenerated right after a login?

    Answer

    Because an id known before the login must not carry the logged-in session

    A fixed id that the attacker planted would otherwise become the id of the logged-in user.

  4. What travels to the browser in a default PHP session?

    Answer

    Only the random session id, in a cookie

    The values stay in a file on the server, and the cookie carries the key to that file.

  5. What does this program print? <?php $stored = "Mozilla/5.0"; $current = "OtherBrowser/9"; if ($stored !== $current) { echo "reset"; } else { echo "same browser"; }

    Answer

    reset

    The two strings differ, so the comparison takes the branch that clears the session.

  6. What does this program print? <?php $stored = "Mozilla/5.0"; $current = "Mozilla/5.0"; if ($stored !== $current) { echo "reset"; } else { echo "same browser"; }

    Answer

    same browser

    Equal strings fail the strict inequality test, so the else branch runs.

  7. What does this program print? <?php var_dump(session_status() === PHP_SESSION_NONE);

    Answer

    bool(true)

    No session has been started in this program, so the status is PHP_SESSION_NONE.

  8. What does this program print? <?php $cookies = ["PHPSESSID" => "abc123", "theme" => "dark"]; echo isset($cookies["PHPSESSID"]) ? "id present" : "no id";

    Answer

    id present

    The array holds the session key, which is what a request looks like after the browser sends the cookie back.

  9. Why does the agent check fail to stop a determined attacker?

    Answer

    The agent string is easy to copy, so the marker matches

    The check raises the cost of a careless stolen cookie, but anyone who copies the whole request brings its agent too.

  10. What does session_regenerate_id(true) do with the old session record?

    Answer

    It deletes it on the server

    The true argument deletes the old record, so an attacker who holds the old id finds nothing.

The examples call session_start(), session_id(), session_status() and session_save_path(). The programs on this page were run with PHP 8.5.13 (php -v): the pages with php -S 127.0.0.1:8000 and a client that kept the cookie, the rest from the command line.

Article author: Arthur Isaev