The Wayback Machine - https://web.archive.org/web/20261112002436/https://www.geeksforgeeks.org/php/php-sessions/

PHP Sessions

Last Updated : 27 Oct, 2026

A session in PHP stores user-specific data on the server and makes it available across multiple page requests. PHP uses the session_start() function to start or resume a session and the $_SESSION superglobal array to store and retrieve session data.

Common uses of PHP sessions include:

  • User Authentication: Maintain login status across pages.
  • Shopping Carts: Remember items selected by users.
  • User Preferences: Store temporary user-specific settings.
  • Form Data: Preserve information across multiple pages of a form.

PHP Sessions Maintain State Across Multiple Requests

HTTP is a stateless protocol, meaning each request is independent. PHP sessions allow a website to associate multiple requests with the same user.

PHP sessions work as follows:

  • Starting a Session: PHP uses session_start() to start a new session or resume an existing one.
  • Generating a Session ID: PHP identifies the session using a unique session ID.
  • Storing Session Data: PHP stores user-specific information in the $_SESSION array.
  • Identifying the User: By default, the browser stores the session ID in a cookie and sends it with subsequent requests.
  • Retrieving Session Data: PHP uses the session ID to retrieve the associated session data.

By default, PHP stores session data on the server, often in files. The session.save_path directive specifies the location used for file-based session storage.

Note: PHP can be configured to use other session storage mechanisms or session ID transport methods.

PHP Uses session_start() to Start a Session

The session_start() function starts a new session or resumes an existing session based on the session ID received from the browser.

Example:

PHP
<?php
session_start();

echo "Session started successfully.";
?>
  • Call session_start() before sending HTML or other output to the browser unless output buffering or another supported mechanism is configured.
  • PHP creates a new session when no valid existing session is available.
  • Calling session_start() makes the session data available through $_SESSION.

PHP Stores and Retrieves Session Data Using $_SESSION

The $_SESSION superglobal is an associative array that stores and retrieves session variables.

Example: Store Session Data

PHP
<?php
session_start();

$_SESSION['username'] = 'GFG';
$_SESSION['user_id'] = 123;

echo "Session data stored successfully.";
?>

The code stores a username and user ID in the session. These values can be accessed by other PHP pages that start the same session.

Example: Retrieve Session Data

PHP
<?php
session_start();

if (isset($_SESSION['username'])) {
    echo "Welcome, " .
        htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8');
} else {
    echo "Please log in.";
}
?>

Output:

Welcome, GFG
  • session_start() starts or resumes the session.
  • isset($_SESSION['username']) checks whether the username exists.
  • $_SESSION['username'] retrieves the stored username.
  • htmlspecialchars() escapes special HTML characters before displaying the value.

The output assumes that the username was stored in the same session during an earlier request.

PHP Checks Whether Session Variables Exist Using isset()

The isset() function checks whether a session variable exists and is not null. It helps prevent attempts to access session variables that have not been initialized.

Example:

PHP
<?php
session_start();

if (isset($_SESSION['username'])) {
    echo "Welcome, " .
        htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8');
} else {
    echo "Please log in.";
}
?>

This check is useful when displaying user-specific information or verifying whether a session variable is available. However, checking a session variable alone does not replace proper authentication and authorization checks.

PHP Destroys Sessions by Clearing Session Data and Removing the Session

PHP provides session_destroy() to destroy the data associated with the current session. To log out a user completely, clear the session variables and expire the session cookie as well.

Example: Destroy a Session During Logout

PHP
<?php
session_start();

// Clear all session variables
$_SESSION = [];

// Remove the session cookie
if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();

    setcookie(session_name(), '', [
        'expires' => time() - 3600,
        'path' => $params['path'],
        'domain' => $params['domain'],
        'secure' => $params['secure'],
        'httponly' => $params['httponly'],
        'samesite' => $params['samesite']
    ]);
}

// Destroy the session
session_destroy();

echo "Logged out successfully.";
?>
  • $_SESSION = [] clears the session variables in the current request.
  • session_get_cookie_params() retrieves the current session cookie settings.
  • setcookie() expires the session cookie in the browser.
  • session_destroy() destroys the data associated with the current session.

Note: session_destroy() does not automatically clear the $_SESSION array or remove the session cookie. These steps must be handled separately when required.

PHP Provides Built-in Functions to Manage Sessions

PHP provides several functions for working with sessions.

FunctionDescription
session_start()Starts a new session or resumes an existing session.
session_destroy()Destroys the data associated with the current session.
session_regenerate_id()Replaces the current session ID with a new one.
session_unset()Frees all session variables currently registered in the $_SESSION array.
session_write_close()Writes session data and closes the session for further modifications during the request.
session_get_cookie_params()Returns the parameters of the session cookie.

Example: Regenerate a Session ID

PHP
<?php
session_start();

session_regenerate_id(true);

echo "Session ID regenerated.";
?>

Regenerating the session ID after authentication helps reduce the risk of session fixation attacks.

PHP Sessions and Cookies Store Data Differently

PHP sessions and cookies both help maintain information across requests, but they differ in how data is stored and transmitted.

PHP SessionsPHP Cookies
Session data is generally stored on the server.Cookies data is stored in the browser.
The browser typically stores a session ID to identify the session.The browser stores the cookie value itself.
Session data is accessed using $_SESSION.Cookie data is accessed using $_COOKIE.
Session data is managed through PHP's session mechanism.Cookies are created and updated using setcookie().
Session persistence depends on server configuration, session lifetime, and browser behavior.Cookies can have an expiration time to persist across browser sessions.
Session data is not directly exposed in the browser, but session IDs must be protected.Cookie values can be viewed or modified by users unless appropriate protections are applied.

PHP Sessions Require Proper Security Configuration

  • Use HTTPS: Protect session IDs during transmission.
  • Regenerate Session IDs: Call session_regenerate_id(true) after authentication or privilege changes when appropriate.
  • Enable Secure Cookie Attributes: Configure session.cookie_secure, session.cookie_httponly, and session.cookie_samesite according to the application's requirements.
  • Validate Authentication: Verify the user's authentication and permissions before granting access to protected resources.
  • Clear Sessions on Logout: Remove session data and expire the session cookie when the user logs out.
  • Avoid Sensitive Client-Side Data: Store sensitive application data in an appropriately protected server-side session rather than directly in cookies.
Comment