In PHP, the $_SESSION variable is used to store data that is specific to a particular user's session. This data is stored on the server and can be accessed and modified by the PHP script during the user's session. Once the user closes their browser or the session times out, the session data is destroyed.
To use the $_SESSION variable, you first need to start the session using the session_start() function. This function initializes a session or resumes an existing one, and must be called at the beginning of the PHP script, before any output is sent to the browser.
session_start();
Once the session is started, you can store data in the $_SESSION array, like so:
$_SESSION['username'] = 'johndoe'; $_SESSION['is_admin'] = true;
You can also retrieve data from the $_SESSION array in the same way you would from any other array:
$username = $_SESSION['username']; $is_admin = $_SESSION['is_admin'];
Note that the data stored in a session is available across multiple pages and requests, so long as the session is active.
You can use session_destroy() function to end a session, this function remove all session data.
session_destroy();
It's important to note that if you want to store sensitive data such as login credentials or financial information, it's recommended to use an additional encryption layer. And also by default, PHP sessions use a file-based storage mechanism, you can also use other storage mechanism like database.
Here's full example of a simple PHP script that demonstrates how to use the $_SESSION variable:
<?php // start the session session_start(); // check if the 'visits' session variable is set if (!isset($_SESSION['visits'])) { // if not, set it to 1 $_SESSION['visits'] = 1; } else { // if it is, increment it by 1 $_SESSION['visits']++; } // print the number of visits echo "Number of visits: " . $_SESSION['visits']; ?>
In this example, the script starts a session using the session_start() function, and then checks if a session variable named visits has been set. If it has not been set, the script sets it to the value 1. If it has been set, the script increments its value by 1. Finally, the script prints the value of the visits session variable to the browser.
When this script is executed for the first time, it will output:
[[output]]
Number of visits: 1
And each consecutive reload of the page will output the incremented number of visits:
[[output]]
Number of visits: 2
[[output]]
Number of visits: 3
And so on. This simple script allows you to keep track of how many times a user has visited your website.
It's worth noting that session data is not stored in the browser, but rather on the server. And also because of that, if the user closes the browser and comes back to your website later, the counter will reset.
You can add more functionalities or data to your script but I hope this example was helpful in understanding how to use the PHP sessions.
Share With Family & Friends