Here's a problem: HTTP doesn't remember anything. Every request your browser makes to a server is completely independent. The server has no idea who you are, what you did a minute ago, or whether you're logged in. That's why sessions exist. They give your web app a memory.
Starting a Session
To use sessions in PHP, you call session_start() at the very top of your page โ before any HTML output. This tells PHP to either create a new session or resume an existing one. PHP then gives the user a unique session ID, usually stored in a cookie on their browser.
<?php
session_start();
$_SESSION["username"] = "john_doe";
$_SESSION["role"] = "admin";
echo "Session data saved!";
?>
Try it Yourself โ
Storing and Retrieving Session Data
Once a session is started, you can store anything you want in $_SESSION. It works like a regular array. On the next page load, as long as the session is active, that data is still there. Need to check if someone is logged in? Just check if a session variable exists.
<?php
session_start();
if (isset($_SESSION["username"])) {
echo "Welcome back, " . $_SESSION["username"];
} else {
echo "Please log in.";
}
?>
Try it Yourself โ
Why Sessions Exist
HTTP is stateless โ every request stands alone. Without sessions, you'd have to log in on every single page. Sessions solve this by storing a small identifier on the user's browser and all the actual data on the server. That way, your app remembers who the user is across multiple page loads, and you don't have to trust the user to keep track of their own data.