Skip to content

PHP Sessions

Sessions provide a way to store user-specific information (in variables) across multiple page requests. This allows you to maintain state and user data as they navigate your website.

Unlike cookies, session data is typically stored on the server, not the user’s computer. Only a unique session ID is usually stored on the client-side (often in a cookie).

HTTP, the protocol underlying the web, is inherently stateless. This means each request a browser makes to a web server is independent; the server doesn’t automatically remember previous interactions with the same user.

Imagine visiting an online store. Without sessions, you couldn’t add items to a shopping cart because the server would forget what you added on the previous page. Sessions solve this by creating a persistent ‘context’ for a user’s visit.

PHP sessions allow you to store user information (like username, preferences, shopping cart items) in server-side variables associated with a unique session ID. This ID is sent back and forth between the browser and server, allowing PHP to retrieve the correct session data for each user request.

By default, session data lasts until the user closes their browser. For persistent storage beyond the browser session, you would typically use a database.

🔑How it works: When a session starts, PHP generates a unique Session ID (e.g., a1b2c3d4e5f6g7h8). This ID is usually sent to the browser and stored in a cookie. On subsequent requests, the browser sends the Session ID back. PHP uses this ID to find and load the corresponding session data stored on the server (often in temporary files).

A session must be explicitly started or resumed on every page where you want to access session data. This is done using the session_start() function.

Crucially: session_start() must be called before any output is sent to the browser (including HTML, whitespace, or echo statements). This is because it needs to potentially send HTTP headers (like setting the session cookie).

Session variables are stored and accessed via the $_SESSION superglobal array (an associative array).

Let’s create a page (page1.php) to start a session and store some data:

<?php
// 1. Start or resume the session
// MUST be called before any output
session_start();
// 2. Set session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['theme'] = 'dark';
$_SESSION['cart_items'] = ['item1', 'item5'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Session Page 1</title>
</head>
<body>
<h1>Session Started</h1>
<p>Session variables have been set.</p>
<p>Username: <?php echo htmlspecialchars($_SESSION['username']); ?></p>
<p><a href="page2.php">Go to Page 2</a></p>
</body>
</html>
❗Placement: Remember, session_start(); must be at the very top of your script, before the <!DOCTYPE html> tag or any other output.

Now, let’s create a second page (page2.php) to access the data we stored in the session on page1.php.

Again, we must call session_start() first to resume the existing session associated with the user’s Session ID.

<?php
// 1. Start or resume the session
session_start();
// Check if session variables exist before accessing them
$username = isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username']) : 'Guest';
$theme = isset($_SESSION['theme']) ? htmlspecialchars($_SESSION['theme']) : 'light';
?>
<!DOCTYPE html>
<html>
<head>
<title>Session Page 2</title>
<style>
body { background-color: <?php echo ($theme === 'dark' ? '#333' : '#fff'); ?>; color: <?php echo ($theme === 'dark' ? '#fff' : '#000'); ?>; }
</style>
</head>
<body>
<h1>Welcome Back, <?php echo $username; ?>!</h1>
<p>Your chosen theme is: <?php echo $theme; ?></p>
<h2>All Session Data:</h2>
<pre>
<?php
// Display all session data for debugging (use carefully in production)
print_r($_SESSION);
?>
</pre>
<p><a href="page1.php">Back to Page 1</a></p>
<p><a href="logout.php">Log Out (Destroy Session)</a></p>
</body>
</html>

Using isset() before accessing $_SESSION variables is good practice to avoid warnings if a variable hasn’t been set yet.

print_r($_SESSION); is useful during development to see all variables currently stored in the session.

To change the value of a session variable, simply overwrite the element in the $_SESSION array. Make sure session_start() has been called.

<?php
session_start();
// Modify the theme variable
if (isset($_SESSION['theme'])) {
$_SESSION['theme'] = 'light';
echo "Theme changed to light.";
} else {
echo "Theme variable not set initially.";
}
// Add an item to the cart array
if (!isset($_SESSION['cart_items']) || !is_array($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = []; // Initialize if not exists or not an array
}
$_SESSION['cart_items'][] = 'item12'; // Add new item
echo "<br>Updated session data:";
print_r($_SESSION);
?>

When a user logs out, or when you want to completely clear their session data, you need to destroy the session.

The standard procedure involves three steps:

  1. Start or resume the session with session_start().
  2. Unset all session variables using session_unset() or by assigning an empty array $_SESSION = array();.
  3. Destroy the session itself using session_destroy(). This removes the session data from the server storage.

Optionally, you might also want to remove the session cookie from the user’s browser to ensure complete cleanup.

Example (logout.php):

<?php
// 1. Start the session
session_start();
// 2. Unset all session variables
$_SESSION = array(); // Or session_unset();
// 3. Destroy the session cookie (optional but recommended)
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// 4. Destroy the session
session_destroy();
?>
<!DOCTYPE html>
<html>
<body>
<h1>Logged Out</h1>
<p>Your session has been destroyed.</p>
<p><a href="page1.php">Start Again</a></p>
</body>
</html>

Session Security: It’s important to configure sessions securely in php.ini or via ini_set(). Key settings include session.cookie_httponly (prevents client-side script access to the cookie), session.use_strict_mode (prevents session fixation), and session.cookie_secure (sends the cookie only over HTTPS). Regenerating the session ID upon login (session_regenerate_id(true)) is also crucial to prevent session hijacking.