Session in PHP with Example

Session in PHP is used to store data and make it accessible across all website pages. It is mostly used in login and logout form, multi-step form, etc.

Session data is destroyed automatically when the user closes their browser and also it automatically delete the session data after a specified time if the user does not do any action on the website.

We can destroy session by using php function session_destory() or unset().

 

What is the use of Session?

The session is used to store temporary data which is accessible across all the pages of the website. Sometimes we have a need to store data temporarily like store data of the user when the user logged in and show his id or email on the menu bar then we use the session to accomplish this work.

It is mostly used in login and logout form, multi-step form.

Sometimes we want to restrict some pages we want these pages should be accessible after login then we can do this by using session.

 

How to use Session in PHP?

To use session in PHP there are the following steps:

  1. You need to start the session by using session_start().
  2. You have to store data in the session variables by using $_SESSION[‘’] globals.
  3. Now you can access the session data by using $_SESSION[‘’]  globals.


Example:  Store Session Data

<?php
 
session_start();
 
$_SESSION['userdata']="hello session";
 
 
?>
 


Example:  Access Session Data

<?php
 
session_start();
 
echo $_SESSION['userdata'];
 
?>
 


How to Destroy a Session in PHP

To destroy session data there are two functions in PHP :

session_destory(): session_destroy() function destroyes all the session variable of the website.

unset(): unset() function destroy a particular session variable.


Example:  Destroy session by using session_destroy()

<?php
 
session_start();
 
session_destroy();
 
?>


Example: Destroy a particular session by using the unset() function

<?php
 
session_start();
 
unset($_SESSION['userdata']);
 
?>
Categories: web development php
Written By : Web Development Institute
Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing Expert Course

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Web Expert with Python

Regular : 12 Months

Fastrack : 6 Months

Crash : 3 Months

Related Blogs

Request For Demo