How to Start, Get and Modify a Session
In this tutorial, we will try to explore How to Start, Get and Modify a Session.
What is a Session?
When you run an application, do some work on it and then you close it. This is like a session. When you start an application the computer knows that it’s you who is using it. But on the internet, the web servers don’t know who you are. So they store user’s information by using a session variable.
How to Start a PHP session?
We can start a PHP session by using the following function:
session_start();
We use PHP global variables to set session variables.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php $_SESSION["favfood"] = "pizza"; $_SESSION["favcar"] = "BMW"; echo "Session variables are successfully set."; ?> </body> </html> |
Get Values from Session Variables
Lets see the code of “Get Values from Session Variables”.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php session_start(
); ?> <!DOCTYPE html> <html> <body> <?php echo "Favorite food is " . $_SESSION["favfood"] . ".<br>"; echo "Favorite car is " . $_SESSION["favcar"] . "."; ?> </body> </html> |
Modifying a PHP Session Variable
Let’s see the code of “Modifying a PHP Session Variable”.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php $_SESSION["favfood"] = "Pasta"; print_r($_SESSION); ?> </body> </html> |
Delete PHP Session
To delete/destroy php session variables, we use “session_unset()” and “session_destroy()”:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php session_unset(); session_destroy(); echo "All the session variables are now destroyed and the session is destroyed." ?> </body> </html> |