Sessions
A session is a server-side store that holds values for one visitor across requests. PHP reads and writes those values through the $_SESSION array.
Two values set and read back
session_start runs first here. Two keys then store a name and a city, and two echo lines read them back.
<?php
session_start();
$_SESSION["name"] = "Hana";
$_SESSION["city"] = "Oslo";
echo $_SESSION["name"] . "\n";
echo $_SESSION["city"] . "\n";A counter rises in the session
The visits key starts at 0. Each step adds 1 to the stored value and prints the new value.
<?php
session_start();
$_SESSION["visits"] = 0;
$_SESSION["visits"] = $_SESSION["visits"] + 1;
echo $_SESSION["visits"] . "\n";
$_SESSION["visits"] = $_SESSION["visits"] + 1;
echo $_SESSION["visits"] . "\n";
$_SESSION["visits"] = $_SESSION["visits"] + 1;
echo $_SESSION["visits"] . "\n";One key removed, one key stays
unset removes the theme key here. The isset checks print false for the removed key and true for the name key.
<?php
session_start();
$_SESSION["name"] = "Hana";
$_SESSION["theme"] = "dark";
unset($_SESSION["theme"]);
var_dump(isset($_SESSION["theme"]));
var_dump(isset($_SESSION["name"]));
echo $_SESSION["name"] . "\n";Example
<?php
session_start();
$_SESSION["user"] = "Hana";
$_SESSION["cart"] = 0;
$_SESSION["cart"] = $_SESSION["cart"] + 1;
$_SESSION["cart"] = $_SESSION["cart"] + 1;
echo "User: " . $_SESSION["user"] . "\n";
echo "Items in cart: " . $_SESSION["cart"] . "\n";Key points
- Use session_start to start a session or to resume one.
- session_start is the first statement in every program in this lesson.
- The server keeps the session values between requests.
- The runs here set values and read them back in a single program run.
- Use a key in $_SESSION to name each stored value.
- unset removes one key from $_SESSION and leaves the other keys in place.
In this example, session_start runs first and opens the session store. The user key holds Hana and the cart key starts at 0. Two steps add 1 each, so the cart line prints 2.
Note
Across requests the server keeps the session, while this lesson shows one run at a time.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which statement must run first in a session program in this lesson?