PHP › Sessions & Cookies
What is a session in PHP, and how does it let a web application remember information about a user across multiple separate page requests?
BeginnerAnswer
A session lets a web application store data related to a specific visitor on the server side and retrieve that same data on later requests from the same visitor, and since HTTP itself is stateless, meaning each request is normally treated independently with no memory of previous requests, PHP achieves this continuity by assigning the visitor a unique session identifier, usually stored in a cookie in their browser, which is then sent back with every subsequent request so the server can look up the correct stored session data.
session_start();
$_SESSION['user_id'] = 42;
// On a later page
echo $_SESSION['user_id'];Real-world example An online store uses a session to remember which items a shopper has added to their cart as they browse different product pages, without needing the shopper to log in or resend that cart information with every single request.