How to Start and Use Sessions in PHP
This article explains what a PHP session is, how it works to store user data across multiple web pages, and the exact steps required to start and manage one in your web applications. You will learn the basic syntax for starting a session, how to store and retrieve session variables, and how to safely destroy a session when it is no longer needed.
What is a PHP Session?
A PHP session is a way to store information (in variables) to be used across multiple pages of a website.
Unlike a cookie, which stores data on the user’s computer, session data is stored securely on the web server. A session allows you to identify a unique user and persist their state—such as login credentials, shopping cart items, or user preferences—as they navigate from one page to another.
How to Start a PHP Session
To start a session in PHP, you must use the
session_start() function. This function must be called at
the very beginning of your PHP file, before any HTML tags, whitespace,
or output are sent to the browser.
<?php
// Start the session
session_start();
?>When session_start() is called, PHP checks if a session
already exists. If it does, PHP resumes the existing session; if not, it
creates a new one and generates a unique session ID for the user.
Storing and Retrieving Session Data
Once the session is started, you can store data using the
$_SESSION superglobal associative array.
Storing Data
To save information in a session, assign a value to a key in the
$_SESSION array:
<?php
session_start();
// Store session data
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "Admin";
?>Retrieving Data
To access this data on another page, you must start the session again
on that page and read from the $_SESSION array:
<?php
session_start();
// Retrieve session data
if (isset($_SESSION["username"])) {
echo "Welcome back, " . $_SESSION["username"];
} else {
echo "Welcome, Guest";
}
?>How to Modify Session Variables
You can modify a session variable by simply overwriting its existing
value in the $_SESSION array:
<?php
session_start();
// Overwrite the existing username
$_SESSION["username"] = "JaneDoe";
?>How to Destroy a PHP Session
When a user logs out or you no longer need the session data, you should clear and destroy the session. This is a two-step process:
- Unset all session variables: Use
session_unset()to remove all session variables. - Destroy the session: Use
session_destroy()to completely destroy the session on the server.
<?php
session_start();
// Remove all session variables
session_unset();
// Destroy the session
session_destroy();
?>