PHP Sessions
A PHP session stores user data on the server between requests, using a single cookie to link each visitor to their own data.
Why sessions exist
Cookies keep data in the browser, but a session keeps the data on the server and gives the browser only a small session ID. This is safer for anything private, because the visitor never sees or controls the stored values. Sessions are the usual way to remember a logged-in user, a shopping cart, or a multi-step form as a person moves from page to page.
When you call session_start(), PHP looks for an existing session ID in the request. If it finds one it loads the matching data; if not, it creates a new session and sends a fresh ID back to the browser as a cookie. Like setcookie(), session_start() sends headers, so it must run before any output.
Starting a session and storing data
<?php
session_start();
// Store values for this visitor
$_SESSION["user_id"] = 42;
$_SESSION["favourite_colour"] = "teal";
echo "Session values have been saved.";
?>Reading session data on another page
Every page that needs the stored data must call session_start() first. After that, the $_SESSION array holds whatever you saved earlier during the same session. Checking with isset() keeps the code safe when a value was never set.
Using stored session values
<?php
session_start();
if (isset($_SESSION["user_id"])) {
echo "Your user id is " . $_SESSION["user_id"] . ".<br>";
echo "Favourite colour: " . $_SESSION["favourite_colour"];
} else {
echo "No active session data found.";
}
?>Changing and removing values
Updating a session value is just a matter of assigning to the array again. To remove a single value use unset(); to clear everything at once use session_unset(). When a user logs out you usually want to destroy the whole session with session_destroy().
Clearing a session on logout
<?php
session_start();
// Remove one value
unset($_SESSION["favourite_colour"]);
// Remove all values and end the session
$_SESSION = [];
session_destroy();
echo "You have been logged out.";
?>- Sessions are ideal for private data because the values stay on the server.
- Every page using the session must call session_start() before any output.
- Session data usually expires after a period of inactivity set by the server configuration.
- Destroy the session on logout so the next visitor cannot reuse it.
Exercise: PHP Sessions
What must be true for $_SESSION data to be readable in a script?