Tuesday, March 10, 2020

Session in PHP

What is a session?

In general, a session refers to a frame of communication between two mediums. A PHP session is used to store data on a server rather than the computer of the user. Session identifiers or SID is a unique number that is used to identify every user in a session-based environment. The SID is used to link the user with his information on the server like posts, emails, etc.

Below are different steps involved in PHP sessions:

Starting a PHP Session: The first step is to start up a session. After a session is started, session variables can be created to store information. The PHP session_start() function is used to begin a new session. It also creates a new session ID for the user.
Below is the PHP code to start a new session:
 <?php 
 session_start();   
 ?>    
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a session. Below is the PHP code to store a session with two session variables user_id and user_name:
<?php 
session_start();
$_SESSION["user_id"] = 101;  
$_SESSION['user_name'] = 'Ajay; 
?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array. The PHP code to access a session data with two session variables user_id and user_name is shown below:
<?php   
session_start();
echo 'The Session id of the user is :' . $_SESSION["user_id"] . '<br>';  
echo 'The name of the user is :' . $_SESSION['user_name'] . '<br>'; 
?>

Output:
The session id of the user is :101
The Name of the user is: Ajay 

Destroying Certain Session Data: To delete only a certain session data, the unset feature can be used with the corresponding session variable in the $_SESSION associative array. The PHP code to unset only the “user_id” session variable from the associative session array:
 <?php   
 session_start();   
 session_unset();    
 if(isset($_SESSION["user_id"])){   
 }   
 else  
 {  
 echo "User Session has been Expired";  
 }  
 ?> 
Destroying Complete Session: The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.
 <?php   
 session_start();   
 session_destroy();   
 ?>