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
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
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.
1 2 3 4 5 6 7 8 9 10 | <?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?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.
1 2 3 4 5 6 7 8 9 | <?php // start a session session_start(); // destroy session session_destroy(); ?> |
That’s it for today.
Thank you for reading. Happy Coding!