How to use session in PHP

In this article, we will explain to you how to use session in PHP. 

A session is a method which is used to store information on the server. It can be accessed in multiple webpages. We use $_SESSION to create and retrieve the session variables and it is a super global variable. To store the information in session, we need to start the session using the session_start() function.

 

1. Create Session variable

Here, we show how to create session variables. We take one example to store logged in user details in session which will be retrieved in all other web pages.

 


session_start();
 
// create session variables
$_SESSION[`user_id`] = `1`;
$_SESSION['user_name'] = `tagStack`; 

 

2. Retrieve Session variable

In other webpages we don`t need to set the value of session variables. Using $_SESSION global variable we can retrieve the data after starting the session by session_start() function.

 


// start a session
session_start();
 
// retrieve session variables
echo "User Id : " .$_SESSION[`user_id`]."";
echo "User Name : " .$_SESSION[`user_name`];
 

 

3. Destroy Session variable

We can remove session variables using the unset function. If we want to remove $_SESSION['user_id'] then we can write as below.

 


// start a session
session_start();
 
print_r($_SESSION);
 
// destroy session variable
unset($_SESSION[`user_id`]);
 
print_r($_SESSION);
 

 

4. Destroy Session

We can remove all sessions using session_destroy() like below.

 


// start a session
session_start();
 
// destroy session
session_destroy();
 

31-August 4:06 PM 388 Views

 Prev question

Next question