PHP Sessions with Examples
In this tutorial, you’ll learn everything about PHP sessions that are an important part of any web application. A session in PHP is a way to store user data in variables that can be used across multiple pages.
Unlike a cookie, where the data is stored on the client’s browser, session data is stored on the web server for later use in a web application. As a result, sessions are generally more secure than cookies. Sessions can also work even when the user has disabled cookies in their browser.
Sessions are stored on the web server in temporary files. They are only kept during the duration of a user’s visit. Once the user leaves the website or the session expires, PHP will destroy the session files. Each session has its own unique identifier (session ID) automatically generated by the user when the session is created.
The main purpose of using PHP sessions is to track user activity and store information, such as names, e-mail addresses, pages visited, and other text-based data. They allow you to maintain user information as the user navigates through different pages on a website.
Need for Session Variables in PHP
When you work with an application, you open it, make some changes, and then close it. This is similar to how a session works. The computer knows who you are, when you start the application, and when you stop using it. However, on the internet, there is a problem: the web server has no idea who you are or what you are doing, because the HTTP protocol is stateless and does not keep track of user activity between requests.
Session variables solve this problem by storing user data that can be accessed across multiple web pages. Each session is assigned a unique session ID, which ensures that one user’s data does not get mixed up with another user’s data when visiting the same website.
By default, session variables last until the user closes the browser or the session times out. This means that session variables hold information about a single user and are available to all pages within the same web application.
Common Uses of Session Variables
Session variables are widely used in web development for tasks such as:
- Login systems – storing user authentication details.
- Shopping carts – keeping track of items added by a user.
- User preferences – storing language choice, theme, or settings.
- Tracking user activity – storing pages visited, form inputs, or temporary data.
Starting a PHP Session
Before you can store user information in a PHP session, you must first start the session. Sessions in PHP are started using the built-in function session_start(). Similar to the setcookie() function, you must always call session_start() before any HTML output; otherwise, PHP will throw a “headers already sent” error.
The following example demonstrates how to start a session in PHP:
<?php
// Start the session.
session_start();
?>
<html>
<body>
</body>
</html>
Storing and Accessing Session Variables
Once a session starts, you can create, access, and modify session variables using the $_SESSION superglobal array. The $_SESSION is a superglobal associative array in PHP that is used to store and retrieve session variables.
Once a session is started using session_start(), you can store information inside $_SESSION and access it across multiple pages. Its basic syntax is as follows:
$_SESSION['key'] = value;
In the above syntax:
- $_SESSION → A predefined associative array in PHP used to store session variables.
- ‘key’ → Represents the name of the session variable (for example, “username”).
- value → Represents the data you want to store. The value can be a string, number, array, object, or any other data type supported by PHP.
Example 1: Storing and Accessing Session Variables
<?php
// Start the session.
session_start();
// Store session variables.
$_SESSION["username"] = "John Doe";
$_SESSION["email"] = "john@gmail.com";
// Access and display session variables.
echo "Username: " . $_SESSION["username"] . "<br>";
echo "Email: " . $_SESSION["email"];
?>
Output: Username: John Doe Email: john@gmail.com
In this example, you learned how to store a variable in the session associative array $_SESSION and how to retrieve session data from the same array.
Example 2: Using $_SESSION
Across Multiple Pages
page1.php
<?php
session_start();
// Store session variable.
$_SESSION["user"] = "Deepak";
echo "Session variable is set. <a href='page2.php'>Go to Page 2</a>";
?>
page2.php
<?php
session_start();
// Access session variable.
echo "Welcome back, " . $_SESSION["user"];
?>
On page1.php →
Output: Session variable is set. [Go to Page 2]
On page2.php →
Output: Welcome back, Deepak
Example 3: Pageviews Counter
<?php
// Start the session.
session_start();
// Check if the session variable 'views' exists.
if (isset($_SESSION['views'])) {
// If it exists, increment it by 1.
$_SESSION['views'] = $_SESSION['views'] + 1;
} else {
// If it does not exist, initialize it to 1.
$_SESSION['views'] = 1;
}
// Display the number of views.
echo "This page has been viewed " . $_SESSION['views'] . " time(s).";
?>
First visit →
Output: This page has been viewed 1 time(s).
After refreshing →
Output: This page has been viewed 2 time(s).
This is a real-world example of using sessions in PHP to track user activity. In this example, the isset() function checks whether the session variable “views” has already been set. If “views” exists, the counter is incremented by 1. If “views” does not exist, a new session variable “views” is created and initialized to 1.
Modify Session Variable
If you want to modify or update the session variable, simply overwrite the values of variables.
Example: Modifying Session Variable
<?php
// Start the session.
session_start();
// Store session variables.
$_SESSION["username"] = "John Doe";
$_SESSION["email"] = "john@gmail.com";
// Change the value of username.
$_SESSION["username"] = "Jane Smith";
// Access and display session variables.
echo "Updated Username: " . $_SESSION["username"];
?>
Output: Updated Username: Jane Smith
In this example, we have changed the value of username from “John Doe” to “Jane Smith” by simply overwriting it.
Destroying a Specific Session Variable
If you need to destroy or remove specific session data, you can use the unset() function. This function removes a particular session variable from the current session without destroying the entire session. Its general syntax is given below:
unset($_SESSION['variable_name']);
In the above syntax,
- $_SESSION[‘variable_name’] is the session variable you want to delete.
Example: Removing a Specific Session Variable
<?php
// Start the session.
session_start();
// Set session variables.
$_SESSION['username'] = "JohnDoe";
$_SESSION['email'] = "john@gmail.com";
echo "Before unset:<br>";
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Email: " . $_SESSION['email'] . "<br>";
// Remove the 'email' session variable.
unset($_SESSION['email']);
echo "<br>After unset:<br>";
echo "Username: " . $_SESSION['username'] . "<br>";
// Check if 'email' exists
if (isset($_SESSION['email'])) {
echo "Email: " . $_SESSION['email'];
} else {
echo "Email session variable is removed.";
}
?>
Output: Before unset: Username: JohnDoe Email: john@example.com After unset: Username: JohnDoe Email session variable is removed.
In this example, we have used the unset() function that removes a specific session variable without affecting other session variables. To destroy all session variables, you use session_destroy() function instead of it.
Destroying a Complete Session
If you wish to end the current session and delete all session variables in the process, use the session_destroy() function. The session_destroy() function is a built-in function that completely destroys a session and removes all session data stored on the server.
Unlike unset(), which removes only specific session variables, the session_destroy() function removes the entire session and all associated data. It is improtant to note that you must call session_start() before using session_destroy() because it operates on the current session.
The general syntax to use session_destroy() function in PHP is as:
session_destroy();
The session_destroy() function does not accept any parameters. This function returns true if the operation is successful. Otherwise, it returns false.
Example 1: Basic Session Destroy
<?php
// Start the session
session_start();
// Set some session variables with data.
$_SESSION['username'] = "Saanvi Kumari";
$_SESSION['email'] = "saanvi@gmail.com";
echo "Before destroying the session:<br>";
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Email: " . $_SESSION['email'] . "<br>";
// Destroy the complete session.
session_destroy();
echo "<br>Session destroyed!";
?>
Output: Before destroying the session: Username: Saanvi Kumari Email: saanvi@gmail.com Session destroyed!
Important Note: The session variables may still be accessible in the current script until it ends. To immediately remove session variables in the current script, use session_unset() function before session_destroy(). This is because the session_destroy() function does not delete session variables immediately in the current script. They will still exist until the script ends.
Example 2: Logout Function Using session_destroy()
A common use case for session_destroy() function is to log out a user.
logout.php
<?php
session_start();
// Remove all session variables immediately.
session_unset();
// Destroy the session.
session_destroy();
echo "You have been logged out.<br>";
echo "<a href='login.php'>Login Again</a>";
?>
Output: You have been logged out. Login Again
In this example, the session_start() function initializes the current session. The session_unset() function removes all session variables from memory, and the session_destroy() function deletes the session from the server completely. As a result, the user is effectively logged out.
PHP Session ID
Every session has a unique session ID. You can access it with built-in session_id() function provided by PHP.
Example 1: Accessing Session ID
<?php
session_start();
echo "Session ID: " . session_id();
?>
Output: Session ID: c2tfio2dard292cgk4nofqad44
This ID is crucial for tracking users across navigating pages.
Example 2: Passing Session ID via URL
If cookies are disabled in the browser, PHP can pass the session ID in the URL.
<?php
session_start();
echo '<a href="page2.php?' . SID . '">Go to Page 2</a>';
?>
In this example, SID is a constant that contains the session ID if cookies are disabled.
Real-Time Example: PHP Login System with Sessions
In PHP, we commonly use sessions in login systems. Let’s take a realtime example in which we will make a simple login system with session handling. First, we will create an HTML form where a user can enter their username and password. The HTML form will look like this:
login.html
<!DOCTYPE html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Now, we create a login.php an authentication page, which is a PHP script. This script will verify the submitted data username and password from the HTML form via the POST method. If the credentials are valid, it establishes a “logged-in state” by setting a session variable (like $_SESSION[‘username’]). Once logged in, it redirects the user to welcome.php (the protected page). If the credentials are invalid, it shows an error message instead of redirecting.
<?php
// Start the session.
session_start();
// Check if form is submitted via POST method.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
// Here, we are taking static username & password for demo purposes.
// In real apps, you can validate against a database.
if ($username == "admin" && $password == "12345") {
// Store username in session.
$_SESSION['username'] = $username;
// Redirect to welcome.php
header("Location: welcome.php");
exit; // Always call exit after header redirect
} else {
echo "Invalid username or password.";
}
}
?>
Let’s create the third file, welcome.php which acts as a protected page. This script shows the user activity log in real time only if the user is logged in. If the user is logged in, it can display a welcome message.
<?php
session_start();
// Check if the user is logged in.
if (isset($_SESSION['username'])) {
echo "Welcome back, " . $_SESSION['username'] . "!<br>";
echo "<a href='logout.php'>Logout</a>";
} else {
echo "Please login first. <a href='login.html'>Login here</a>";
}
?>
At last, let’s create the fourth file (logout.php) which is responsible for:
- Starting the session so that PHP knows which session to destroy.
- Removing all session variables using session_unset().
- Destroying the session completely using session_destroy().
- Redirecting the user (commonly back to login.html or a homepage).
<?php
session_start();
// Remove all session variables.
session_unset();
// Destroy the session.
session_destroy();
echo "You have been logged out.<br>";
echo "<a href='login.html'>Login Again</a>";
?>
Output:
PHP Session Functions
PHP provides several functions to handle sessions. Some of important functions which are not used in the above programs are as follows:
- session_cache_expire(): Returns the current cache expiration time for session pages. By default, it is 180 minutes (3 hours) unless changed with session_cache_expire($minutes).
- session_decode(): Decodes the session data.
- session_encode(): Encode the current session data as a string.
- session_get_cookie_params(): Returns an associative array of cookie parameters such as lifetime, path, domain, secure, and httponly of the current session.
- session_module_name(): Returns the name of the current session module (by default “files”). If you pass a module name as a parameter, it will set that module and return the previous one.
- session_name(): Returns the name of current session (default is “PHPSESSID”). If a name is specified, it changes the name of the current session and returns the old name.
- session_regenerate_id(): Generates a new session ID to replace the current one and keeps the current session data.
- session_register(): Registers one or more global variables with the current session.
- session_save_path(): Returns the current directory path used to store session data. If a path is specified, it sets a new path and returns the old one.
- session_write_close(): Stores the session data and closes the session.
Best Practices for PHP Sessions
When working with PHP sessions, keep the following points in mind:
- Always call session_start() at the top of the page before any HTML output.
- Use session_regenerate_id() regularly to prevent session fixation attacks.
- Avoid storing sensitive data (like passwords) directly in session variables.
- Always destroy sessions after logout using session_unset() and session_destroy().
- Use HTTPS to protect session cookies from being intercepted.
Conclusion
PHP sessions are a powerful way to manage user state across multiple pages in a web application. From simple login systems to shopping carts and personalized dashboards, sessions are an essential part of secure and dynamic websites.
In this guide, we covered:
- Basics of PHP sessions.
- Syntax and examples for creating, modifying, and destroying sessions.
- Real-world login system example.
By following the best practices and examples in this tutorial, you can confidently use PHP sessions to build secure and user-friendly applications.