Creating and destroying a session


What is a session ?

The session is a simple way to store data of individual users in a unique session id. Session ids are sent via session cookies to the browser; these ids are used to retrieve existing data. When there is no session-id present, it tells PHP to create a new session and generate a unique session id. The session works on a simple workflow. When it starts, PHP retrieves a session using the session id, or if there is no session, it creates a new one. Using $_SESSION, it performs all the operations. Session stores information in the form of variables; unlike cookies, it doesn't store information on the user's computer. When you open any application, make some changes and close it. That application stores your changes or accepts them, but the internet doesn't know you. It always requires verification; a session solves this problem. It stores the user's information and provides it to the internet.

Creating a Session

A new session starts using the session_start() function in PHP. PHP uses the super variable $_SESSION to perform all the operations on a session. 

Syntax :

  session_start(); // Starts the session

Creating a Session Example

<?php session_start(); $_SESSION["Rollnumber"] = "15"; $_SESSION["Name"] = "Aashish"; ?>
<?php session_start(); echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>'; echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>'; ?>

output:

The Name of the student is :Aashish The Roll number of the student is :15

Destroying a session

To remove all used super variables and to destroy the session PHP uses session_unset() and session_destroy() methods respectively. 

Syntax : 

session_unset() // removes all the session variables 

session_destroy() // Destroy the session.

Destroying a session Example

<?php session_start(); if(isset($_SESSION["Name"])){ unset($_SESSION["Rollnumber"]); } ?>
<?php session_start(); session_destroy(); ?>