← Back to PHP Course | Chapter 12: Sessions & Cookies | Lesson 1 of 5

PHP Sessions Introduction

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
<?php
session_start();
$_SESSION['username'] = "Alice";
echo "Only the session ID is stored in the browser's cookie";
?>

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
<?php
session_start();
$_SESSION['user_id'] = 5;
echo "Stored user_id in the session";
?>

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
<?php
session_start();
$_SESSION['user_id'] = 5;
echo "Logged in as user #" . $_SESSION['user_id'];
?>

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
<?php
session_start();
$_SESSION['cart'] = ["item1", "item2"];
unset($_SESSION['cart'][0]);
print_r($_SESSION['cart']);
?>

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
<?php
session_start();
$_SESSION['user_id'] = 5;
session_unset();
session_destroy();
echo isset($_SESSION['user_id']) ? "Still logged in" : "Logged out completely";
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.