Skip to main content

PHP Sessions

By SamK
0
0 recommends
Topic(s)

A session is a method for storing temporary information in variables that can be accessed across multiple pages.

The session variables are mainly used to track who the current user is and what that user is doing on website. You can use session variables to store user-specific information for use across multiple pages (such as username, favorite color, etc.). By default, session variables remain active until the user closes the browser.

In contrast to cookies, the session information is not saved on the user's computer.

Note: For permanent storage, consider saving your data in a database.

Start a PHP Session

A session is initiated using the session_start() function.

Session variables are managed with the global PHP variable: $_SESSION.

Example:

<?php
// Start the session
session_start();
// Set session variables
$_SESSION["name"] = "John";
$_SESSION["gender"] = "Male";
?>

Note: The session_start() function must be the very first statement in your document, placed before any HTML tags.

Retrieve Session Values

All session variable values are stored in the global $_SESSION array. So, you can use this array to retrieve the session values.

Example:

<?php
session_start();

// Display session variables that were set on the previous page
if (isset($_SESSION["name"]) && isset($_SESSION["gender"])) {
    echo "Name: " . htmlspecialchars($_SESSION["name"]) . "<br>";
    echo "Gender: " . htmlspecialchars($_SESSION["gender"]);
} else {
    echo "No session variables are set.";
}
?>

/*
Output:
Name: John
Gender: Male
*/

Note: Session variables are not transferred individually to each new page; rather, they are accessed from the session that we start at the beginning of each page using session_start().

Modify a Session Variable

To update a session variable, simply assign it a new value.

<?php
session_start();

// Update session variables by assigning new values
$_SESSION["name"] = "Jane";
$_SESSION["gender"] = "Female";

if (isset($_SESSION["name"]) && isset($_SESSION["gender"])) {
    echo "Name: " . htmlspecialchars($_SESSION["name"]) . "<br>";
    echo "Gender: " . htmlspecialchars($_SESSION["gender"]);
} else {
    echo "No session variables are set.";
}
?>

/*
Output:
Name: Jane
Gender: Female
*/

Destroy a PHP Session

To clear all session variables and end the session, use session_unset() followed by session_destroy().

<?php
session_start();

// Remove all session variables
session_unset();

// Destroy the session
session_destroy();
?>

Questions & Answers