Sessions
Learn how PHP sessions store data on the server for each visitor and how they compare to cookies.
Introduction
Cookies are useful, but storing sensitive data directly in the browser is risky — a visitor can view or edit anything a cookie holds. PHP sessions solve this by keeping the actual data safely on the server, and using just a single small cookie to identify which visitor's data belongs to which request.
This lesson covers how sessions work, how to start one with session_start(), how to store and retrieve values with $_SESSION, and how sessions compare to the cookies you learned about in the previous lesson.
- What a session is and how it relates to a session ID cookie.
- How to start a session with session_start().
- How to store and read data using the $_SESSION superglobal.
- How to end a session with session_destroy().
- Why session_regenerate_id() matters for security, and how sessions compare to cookies.
What is a Session?
A session is a way to store data on the server that persists across multiple page requests from the same visitor. When a session starts, PHP generates a unique session ID, stores it in a cookie on the visitor's browser, and uses that ID to look up the matching data — stored server-side — on every later request.
Data Lives on the Server
Unlike a cookie, the actual session data never leaves the server.
Identified by a Cookie
A single session ID cookie (usually named PHPSESSID) links each request back to its stored data.
Safer for Sensitive Data
Because visitors cannot read or edit the underlying data, sessions suit things like login state.
Temporary by Default
A session typically ends when the browser closes, unless configured otherwise.
Starting a Session
Before you can use $_SESSION, you must call session_start(). This must happen before any output is sent to the browser, just like setcookie(), because it involves sending an HTTP header behind the scenes.
<?php
session_start();
echo "Session started. ID: " . session_id();
?>Session started. ID: 8f3ka92ldk3jf83nfk23session_start() must be the very first thing that runs — before any echo, HTML, or whitespace outside the <?php tag — or PHP will raise a "headers already sent" warning.
Storing and Reading Session Data
Once a session has started, $_SESSION behaves like a regular associative array. Anything you store in it on one page is automatically available on any other page during the same session, as long as session_start() runs first each time.
<?php
session_start();
$_SESSION["username"] = "rahul";
$_SESSION["logged_in"] = true;
echo "Session data saved.";
?><?php
session_start();
if (!empty($_SESSION["logged_in"])) {
echo "Welcome back, " . htmlspecialchars($_SESSION["username"]) . "!";
} else {
echo "You are not logged in.";
}
?>Welcome back, rahul!Ending a Session
To fully end a session — typically when a visitor logs out — clear its data with session_unset() and then destroy the session itself with session_destroy().
<?php
session_start();
$_SESSION = [];
session_unset();
session_destroy();
echo "You have been logged out.";
?>You have been logged out.Regenerating the Session ID
session_regenerate_id() replaces the current session ID with a new one while keeping the session's data intact. This is a simple but important security measure, typically called right after a visitor successfully logs in, to prevent an attacker from reusing a previously known session ID.
<?php
session_start();
// After verifying the visitor's login credentials:
session_regenerate_id(true);
$_SESSION["logged_in"] = true;
echo "Login successful, session ID refreshed.";
?>Login successful, session ID refreshed.Regenerating the session ID after login helps prevent session fixation attacks, where an attacker tricks a visitor into using a session ID the attacker already knows.
Sessions vs Cookies
Cookies
- Data stored directly in the browser
- Visitor can view or edit the value
- Set with setcookie() and read with $_COOKIE
- Good for small, non-sensitive preferences
- Size limited to a few kilobytes
Sessions
- Data stored on the server
- Visitor only holds an opaque session ID cookie
- Started with session_start() and used via $_SESSION
- Good for sensitive data like login state
- Can hold much larger and more complex data
In practice, sessions actually rely on a cookie behind the scenes — the session ID itself. The key difference is that the meaningful data stays safely on the server rather than being exposed to the visitor.
Example: A Simple Login Flow
A small end-to-end example showing a session being started, populated on login, checked on a protected page, and cleared on logout.
<?php
session_start();
// Imagine credentials were already verified above.
$_SESSION["username"] = "rahul";
$_SESSION["logged_in"] = true;
session_regenerate_id(true);
echo "Logged in as " . $_SESSION["username"];
?><?php
session_start();
if (empty($_SESSION["logged_in"])) {
echo "Please log in first.";
} else {
echo "Dashboard for " . htmlspecialchars($_SESSION["username"]);
}
?>Logged in as rahul
Dashboard for rahulCommon Mistakes
- Forgetting to call session_start() on every page that needs access to $_SESSION.
- Calling session_start() after some HTML or whitespace has already been output.
- Skipping session_destroy() on logout, leaving stale session data reachable.
- Never regenerating the session ID after login, leaving the application open to session fixation.
- Storing extremely large amounts of data in $_SESSION when a database would be more appropriate.
Best Practices
- Call session_start() at the very top of every script that needs session data.
- Use $_SESSION for anything sensitive, like login state, instead of a plain cookie.
- Always call session_regenerate_id() right after a successful login.
- Fully clear a session with session_unset() and session_destroy() on logout.
- Keep session data reasonably small and focused on what identifies the current visitor.
Frequently Asked Questions
Do I need to call session_start() on every single page?
Yes, any page that needs to read or write $_SESSION must call session_start() first, since PHP does not automatically resume a session otherwise.
What happens if a visitor disables cookies?
Since sessions rely on a session ID cookie by default, sessions will not work reliably without cookies enabled, though PHP can be configured to pass the ID via the URL as a fallback.
How long does a session last?
By default, a session typically ends when the browser closes, but this can be adjusted with session and cookie lifetime settings in php.ini.
Is session_destroy() enough to fully log a visitor out?
It is the key step, but clearing $_SESSION with session_unset() first and, ideally, also expiring the session cookie itself gives a more thorough logout.
Can I store an object or array in $_SESSION?
Yes, $_SESSION can hold arrays and most PHP values directly, since PHP handles the underlying serialization automatically.
Key Takeaways
- A session stores data on the server, tied to a visitor through a session ID cookie.
- session_start() must run before any output and before using $_SESSION.
- Session values are stored and read like a normal array through $_SESSION.
- session_destroy() ends a session, typically used on logout.
- session_regenerate_id() helps protect against session fixation, especially after login.
Summary
Sessions give PHP a secure way to remember information about a visitor across multiple requests without exposing the actual data to their browser. A single session ID cookie is all that travels back and forth, while the meaningful data — like login state — stays safely on the server.
In this lesson, you learned how to start, use, end, and secure a session, and how sessions compare to the cookies from the previous lesson. Next, you will move on to working with dates and times in PHP.
- You understand what a session is and how it relates to cookies.
- You can start a session and store data with $_SESSION.
- You can end a session with session_destroy().
- You know why session_regenerate_id() matters for security.