×

php · level 2 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A remembers one visitor from page to page.

Every request starts your program fresh, with every variable empty. So how does a shop remember your basket? With a session: a store on the server that remembers things about one visitor. The browser keeps a , a small note holding the session's ID, and sends it back with every request.

PHP hands you the visitor's session as the superglobal $_SESSION, an array you can read and change. Whatever you put in it is still there on their next page.

A real site calls session_start() first. Gwecode pretends instead: fill $_SESSION at the top with what the visitor's earlier pages saved.

<?php
$_SESSION = ["visits" => 3, "basket" => ["apple"]];
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;
$_SESSION["basket"][] = "pear";
echo "Visit number {$_SESSION["visits"]}\n";
echo "Basket: " . implode(", ", $_SESSION["basket"]) . "\n";

Keep only what you need in a session, like a basket or the name of whoever is logged in, never their password.