Unsetting php session you must read my previous article
setting php session to get better understand it. Now in Setting php session we had set the username in set.php and in view we had store username into the session. Now we will create another file unset.php which you can say logout the user. Unset is keyword to remove the stored session variable.
Code for Unsetting php session
set.php (Screenshot1)
|
Set.php Screenshot1 |
<?php
session_start();
$_SESSION['username']='alex';
?>
View.php (Screenshot2)
|
Screenshot2 |
<?php
session_start();
if (isset($_SESSION['username'])) {
echo 'Welcome. '.$_SESSION['username']';
}else {
echo 'Please log in.';
}
?>
Unset.php (Screenshot3)
|
Screenshot3 |
<?php
session_start();
unset($_SESSION['username']);
?>
Output (Screenshot4 , Screenshot5 , Screenshot6):-
|
Screenshot4 |
|
Screenshot5 |
|
Screenshot6 |
Now As you can See in Screenshot4 , Screenshot5 We had unset the variables which is stored in session alex and in Screenshot 6 its again asking for please login now You. Try Your self by again setting php Session and Unsetting php Session.
For Example If You will not rewrite session_start() in unset.php. It will not remove variable from the session and session will not be unset.
Let See All output for all set.php , view.php and unset.php
|
Screenshot7 |
Opening set.php file for setting username as a session variable
|
Screenshot8 |
$_SESSION['username']='alex'; is set to the session variable.
|
Screenshot9 |
viewing view.php
|
Screenshot10 |
Shows welcome Alex as we can see the Session variable called alex.
|
Screenshot11 |
Unset.php file opening
|
Screenshot12 |
Will unset the variable which had been set by set.php
|
Screenshot13 |
Now You can see view.php is in condition of else because the session variable is unset by unset.php.
Now What if i have more then one session to unset. If i want to unset all session that exit . For That you can try your self
Code for unsetting php session
unset.php
<?php
session_start();
session_destroy();
?>
Output (Screenshot14 , Screenshot15 , Screenshot16 , Screenshot17)
|
Screenshot14 |
|
Screenshot15 |
|
Screenshot16 |
|
Screenshot17 |
Now this session_destroy will unset all session of the website. It will remove all variables of the session which are stored in session.
In Screenshot 17 you can see all session variable had been removed
No comments:
Post a Comment
Thanks For Comment Will get you Soon..