PHP Sessions Introduction
In this page:
What is a Session?
A session lets your app remember information about one visitor -- like their username or shopping cart contents -- as they move between pages, even though HTTP itself has no memory of previous requests. Unlike cookies, the actual data is stored on the server; the browser only holds a small session ID.
Example: What is a Session?
<?php
session_start();
$_SESSION['username'] = "Alice";
echo "Only the session ID is stored in the browser's cookie";
?>
Login to try C/C++/Java/PHP code in the editor
Storing Session Data
You store session data by writing key-value pairs directly into the $_SESSION superglobal array, for example $_SESSION[user_id] = 5. PHP automatically associates that data with the visitor's session ID behind the scenes.
Example: Storing Session Data
<?php
session_start();
$_SESSION['user_id'] = 5;
echo "Stored user_id in the session";
?>
Login to try C/C++/Java/PHP code in the editor
Retrieving Session Data
As long as session_start() runs at the top of the page, you can read back anything stored earlier in $_SESSION from any script in your app, which is what lets a login persist across an entire site.
Example: Retrieving Session Data
<?php
session_start();
$_SESSION['user_id'] = 5;
echo "Logged in as user #" . $_SESSION['user_id'];
?>
Login to try C/C++/Java/PHP code in the editor
Deleting Session Keys
Calling unset($_SESSION[key]) removes one specific piece of session data without disturbing anything else the user has stored, useful for things like clearing a single cart item.
Example: Deleting Session Keys
<?php
session_start();
$_SESSION['cart'] = ["item1", "item2"];
unset($_SESSION['cart'][0]);
print_r($_SESSION['cart']);
?>
Login to try C/C++/Java/PHP code in the editor
Destroying Sessions
Logging a user out completely means clearing all session data with session_unset() and then destroying the session itself with session_destroy(), so no leftover state can be reused by the next visitor on a shared browser.
Example: Destroying Sessions
<?php
session_start();
$_SESSION['user_id'] = 5;
session_unset();
session_destroy();
echo isset($_SESSION['user_id']) ? "Still logged in" : "Logged out completely";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: