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