PHP Sessions

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.

How to start PHP Sessions:

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 the 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 clicks on the 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"];
?>

As in above example program you can see in the beginning(on 6th line) of the program the value of variable username was Abc but later(on 10th line) we changed this the value of username variable to XYZ. So it means to change the value of session variable you just have to assign a new value to a variable and that’s it.

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 to understand this more wisely.

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();
?>

 

Spread the love
Scroll to Top
×