Learn How PHP Sessions Work In 10 Minutes
Understand how to start, use, and manage sessions in PHP to store user-specific data across pages.
🔑 What Are PHP Sessions?
Sessions in PHP allow you to store data on the server for individual users. Unlike cookies, session data is stored server-side and is more secure. They are commonly used for login systems, shopping carts, and remembering user preferences.
🚀 Starting a Session
You must call session_start()
at the top of your script before
any HTML output:
<?php
session_start();
?>
This function creates a unique session ID and stores it in the user's browser as a cookie.
📦 Storing Session Data
<?php
session_start();
$_SESSION['username'] = 'john_doe';
$_SESSION['role'] = 'admin';
?>
Data is stored in the $_SESSION
superglobal array and will
persist across different pages for that user.
📥 Retrieving Session Data
<?php
session_start();
if (isset($_SESSION['username'])) {
echo "Welcome, " . htmlspecialchars($_SESSION['username']);
} else {
echo "Guest user.";
}
?>
❌ Unsetting and Destroying Sessions
To clear session variables or log out a user:
<?php
session_start();
// Remove one session variable
unset($_SESSION['username']);
// Remove all session variables
session_unset();
// Destroy the session completely
session_destroy();
?>
🔍 Common Use Cases
- Maintaining user login state
- Tracking user behavior across pages
- Storing shopping cart data
- Implementing access control
🔐 Security Tips
- Always use
session_start()
before outputting HTML -
Regenerate session ID after login using
session_regenerate_id(true)
- Use HTTPS to prevent session hijacking
-
Set session cookies as
HttpOnly
andSecure
in production