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:
- You need to start the session by using session_start().
- You have to store data in the session variables by using $_SESSION[‘’] globals.
- 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']);
?>