Site icon T4Tutorials.com

How to Start, Get and Modify a Session

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:

<?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”.

<?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”.

<?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:

<?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>
Exit mobile version