PHP Sessions

By | May 4, 2020

In this tutorial, we will learn about PHP Sessions. PHP sessions are a way to access data among different web pages of the website. All the session variables and their values stored in a file in the temporary directory on the server. With the help of PHP sessions, we can share various kind of data among all the pages of the website such as login_status, username etc. It is important to note that By default, session variables last until the user closes the browser.

Start a Session:

We have session_start() function in PHP to start a session in PHP and to create and set a session variable in PHP we use $_SESSION global variable. Please check out the following example program:

Example Program:

<?php
// Starting the session
session_start();
// Setting session variables and values
$_SESSION["login_status"] = "true";
$_SESSION["username"] = "Abc";
?>

Get PHP Session variables:

After starting a session and creating session variables we can fetch session variables in different web pages of website. Please check out the following example program.

Example Program:

<?php
// Starting the session
session_start();
// Setting session variables and values
$_SESSION["login_status"] = "true";
$_SESSION["username"] = "Abc";

echo "Hello " . $_SESSION["username"];
?>

Modifying session variables:

We can modify session variables any number of times. For example you want to changes login_status to false after user click on logout button. Please check out the following example program.

Example Program:

<?php
// Starting the session
session_start();
// Setting session variables and values
$_SESSION["login_status"] = "true";
$_SESSION["username"] = "Abc";
echo "Hello " . $_SESSION["username"];

//modifying session variable
$_SESSION["username"] = "XYZ";
echo "Hello " . $_SESSION["username"];
?>

Removing session variables:

There are two functions in PHP to remove session variables. First one is session_unset() to remove all the session variables and the second one is session_destroy() is to destroy the complete session. Please check out the following example program.

Example Program:

<?php
// Starting the session
session_start();
// Setting session variables and values
$_SESSION["login_status"] = "true";
$_SESSION["username"] = "Abc";
echo "Hello " . $_SESSION["username"];
// remove all the session variables
session_unset();
// destroy the complete session
session_destroy();
?>