Every request to a PHP script starts fresh. Variables from the previous page are gone. $_SESSION solves that: it is an array that PHP keeps on the server for each visitor between requests.
<?php
session_start(); // must come before using $_SESSION
$_SESSION["user_name"] = "Isha";
On the next page:
<?php
session_start();
echo "Welcome back, " . htmlspecialchars($_SESSION["user_name"] ?? "guest");
How it works
session_start()checks whether the browser sent a session ID cookie.- If not, PHP creates a new session and sends the ID to the browser as a cookie.
- PHP loads the saved data for that ID into
$_SESSION. - When the script ends, PHP saves the changes.
The visitor’s browser only holds the ID. The data lives on the server, so it cannot be changed by the visitor.
What to store
- The ID of the logged-in user (not the whole user record or the password).
- A shopping cart, a CSRF token, a flash message.
- Small things. Sessions are stored per visitor, and large sessions slow everything down.
Rules
- Call
session_start()before any output, because it sends a cookie header. - Call it on every page that uses
$_SESSION. - Never put secrets such as passwords in the session. Store the user’s ID, and load the rest from the database when needed.
Reading safely
<?php
$_SESSION = []; // pretend a new, empty session
$name = $_SESSION["user_name"] ?? "guest";
echo $name;
guest
Chapter 16 covers everything about sessions: What Is a Session?, secure session practices and logging out.