How to use session in PHP
Today we will explain to you how to use session in PHP. Here you can understand how we can start a session, create session variable, retrieve session variable and destroy the session.
How to Create, Access and Destroy Sessions in PHP, How to Use Sessions and Session Variables in PHP, How to use store and use session variables across pages, How do PHP sessions work, How to use session variables in php, Use session in php for login form, session destroy in php, how to store data in session in php, Understanding How PHP Sessions Work.
Checkout more articles on PHP
- email-using-php-mail-function" title="Send an email using PHP mail() function">Send an email using PHP mail() function
- Add or Subtract days, month and year to a date using PHP
- Sorting Arrays in PHP
- string-in-php" title="Remove the last character from a string in PHP">Remove the last character from a string 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.
Way to use session
- csv" title="Create Session variable">Create Session variable
- Retrieve Session variable
- Destroy Session variable
- Destroy Session
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.
<?php
// start a session
session_start();
// create session variables
$_SESSION['user_id'] = '1';
$_SESSION['user_name'] = 'Cluemediator';
?>
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.
<?php
// start a session
session_start();
// retrieve session variables
echo "User Id : " .$_SESSION['user_id']."</br>";
echo "User Name : " .$_SESSION['user_name'];
?>
// Output:
User Id : 1
User Name : Cluemediator
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.
<?php
// 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.
<?php
// start a session
session_start();
// destroy session
session_destroy();
?>
That’s it for today.
Thank you for reading. Happy Coding!