php · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A brand new visitor arrives. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$_SESSION = [];
$_SESSION["visits"] = ($_SESSION["visits"] ?? 0) + 1;
$name = $_SESSION["name"] ?? "stranger";
echo "Hello, $name! This is visit {$_SESSION["visits"]}.\n";
your turn
Your turn. Fill the basket.
The visitor already has milk in their basket. Type two more things to add, then run it.
fix it
Adding bread broke the basket. Can you fix it?
- The TypeError says
implodewas given a string. What is in the basket after line 3? - Line 3 overwrites the whole basket with one string. You want to add an item to the array.
- Add empty square brackets:
$_SESSION["basket"][] = "bread";, then press run.
nailed it
your site remembers its visitors now. :D
- A session remembers one visitor between requests.
$_SESSIONis an array you read and change.- In Gwecode, you fill
$_SESSIONat the top yourself.
new words in your collection
- session
- cookie
This lesson isn’t saved. A free account remembers every lesson you finish.