PHP | Unset Session Variable
Last Updated :
20 Jul, 2020
Whenever data are stored using cookies, there is a possibility of a hacker to insert some harmful data in the user’s computer to harm any application. So its always advisable to use PHP sessions to store information on the server than on a computer. Whenever data is needed across many pages of a website or application, PHP Session is used.
This session creates a temporary file in a folder that stores registered variables with their values which are made available for the entire website. This Session ends when the user logs out of the site or browser. Every different user is given unique session IDs that are linked to an individual’s posts or emails.
<?php
session_start();
echo session_id();
?>
Note: The session IDs are randomly generated by the PHP engine which is difficult to make out.
Example: The following PHP function unregisters or clears a session variable whenever $_SESSION is used in some code. It is mostly used for destroying a single session variable.
Note: The PHP session_start() function is always written in the beginning of any code.
- Program 2:
<!DOCTYPE html>
<html>
<head>
<title>Unset Session Variable </title>
</head>
<body>
<h1 style= "color:green" >GeeksforGeeks</h1>
<b> Unset previous session of user</b>
<?php
echo '<br>' ;
echo '<br>' ;
if (isset( $_SESSION [ "user_name" ]))
{ echo "Welcome " ; echo $_SESSION [ "user_name" ]; }
?>
<form>
Input your name here:
<input type= "text" id= "user_id" name= "user_id" >
<input type=submit value=Submit>
</form>
<form action= "#" >
<input type= "submit" name= "submit"
value= "Unset"
onclick= "UnsetPreviousSession()" >
</form>
<?php
session_start();
if (!isset( $_SESSION [ "user_name" ]) && (! empty ( $_GET [ 'user_id' ])))
{
$_SESSION [ "user_name" ] = $_GET [ "user_id" ];
}
else
{
UnsetPreviousSession();
}
function UnsetPreviousSession()
{
unset( $_SESSION [ 'user_name' ]);
}
?>
</body>
</html>
|
- Output: After clicking the Unset button, the following output screen is visible for re-entry which shows the previous session variable is unset.
Share your thoughts in the comments
Please Login to comment...