Sessions

A session keeps a logged-in state between requests without putting the data into the browser. In PHP the server stores the values and the client only carries a random id.

session_start

A session keeps data on the server across page loads, keyed by a random id stored in a cookie. Call session_start() before any output on every page that needs the session. Background in PHP sessions.

After the call the $_SESSION array is ready for reading and writing.

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

<?php session_start(); echo session_id() === "" ? "no id" : "session started";

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

session started

The response also carries a Set-Cookie: PHPSESSID=... header with the random id. The id itself changes on every fresh session, so the page shows only that one exists; the browser sends it back on the next request and the server finds the same data.

Store in $_SESSION

Treat $_SESSION like a per user storage bag. Save the user id, locale, and flash messages there instead of passing them through URLs and hidden fields.

Store minimal values and reload the rest from the database on each request.

The file store.php in the same folder:

<?php session_start(); $_SESSION["user_id"] = 42; $_SESSION["locale"] = "en"; echo $_SESSION["user_id"], PHP_EOL;

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

42

The two values are written to the session file of this visitor and read back in the same request. The next request with the same id finds them without any help from the URL.

Regenerate id

Fixation attacks reuse a known session id, so change the id at privilege boundaries. Regenerate right after a successful login and before showing account pages. The call is session_regenerate_id() with true as its argument.

The data stays, only the id changes, which drops the old id from future use.

The file regenerate.php in the same folder:

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

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

id changed
42

The two ids differ, and the stored user id survives the change, so a login can move to a fresh id without losing the visitor. The true argument deletes the old session file as well.

Logout and destroy

A correct logout clears the data, removes the session cookie, and destroys the server side record. All three steps matter, otherwise a stale id may remain valid.

Redirect to a public page after logout so a refresh cannot resubmit the action.

The file logout.php in the same folder:

<?php session_start(); $_SESSION["user_id"] = 42; $_SESSION = []; $params = session_get_cookie_params(); setcookie(session_name(), "", [ "expires" => time() - 42000, "path" => $params["path"], ]); session_destroy(); var_dump(isset($_SESSION["user_id"])); echo "logged out", PHP_EOL;

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

bool(false)
logged out

The empty array clears the data, the past expiry deletes the cookie in the browser and the destroy call removes the record on the server, so the same id can no longer load anything. The dump proves the user id is gone before the confirmation line. The name of the cookie comes from session_name() and its path from session_get_cookie_params(), so the expiry reaches the same cookie the session started with; setcookie() writes it and session_destroy() removes the record.

Exercises

  1. Add a counter to store.php that grows by one on every refresh of the same session.
  2. Print the session id before and after session_regenerate_id() without the comparison.
  3. Remove the cookie deletion from logout.php and check whether the browser still sends the old id.
  4. Set a flash message in one request and read it in the next, then delete it after reading.

Questions

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

  1. Where is the data of a session stored?

    Answer

    On the server, and the cookie holds only the id

    The server keeps the values and the client carries a random id that points at them.

  2. What must be called before reading $_SESSION?

    Answer

    session_start()

    The start call loads the session file and fills the array for the current request.

  3. What does session_regenerate_id(true) do?

    Answer

    It creates a new id and deletes the old session record

    The session moves to a fresh id, which defeats a fixation attack, and the old record is removed.

  4. Which step is missing from a logout that only empties $_SESSION?

    Answer

    Deleting the session cookie and destroying the server record

    The id in the browser and the record on the server survive an empty array, so both must go too.

  5. What does this program print? <?php $session = ["user_id" => 42]; echo $session["user_id"];

    Answer

    42

    The key exists in the array and the echo prints the stored integer.

  6. What does this program print? <?php $session = ["user_id" => 42]; unset($session["user_id"]); var_dump(isset($session["user_id"]));

    Answer

    bool(false)

    unset removes the key, and isset then reports false.

  7. What does this program print? <?php $session = ["user_id" => 42]; $session = []; var_dump(isset($session["user_id"]));

    Answer

    bool(false)

    The empty assignment replaces the whole array, so the key is gone.

  8. What does this program print? <?php echo session_name();

    Answer

    PHPSESSID

    session_name returns the name of the session cookie, which is PHPSESSID by default.

  9. Why is the session id changed right after a successful login?

    Answer

    So an id known before the login cannot be reused

    A fixation attack plants an id, and regenerating it after the login takes that id out of use.

  10. What does session_destroy() remove?

    Answer

    The server side record of this session

    The call deletes the stored record; the cookie has to be expired separately with setcookie.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev