Sometimes it is necessary to destroy a session. If you are familiar with a log in system, usually there is a “Log Out” too. Essentially, when you log in, you have a session, when you log out, that session is destroyed so others cannot latch onto the old data and leach out your personal info for their nefarious purposes. Here I demonstrate a quick and dirty not-so-realistic log in system and a way to log out. I also prove that the session is destroyed by showing a certain page’s differences when I am logged in and not.
Here are the sources used in this tutorial:
login.php
<?php //fake login php session_start(); if((int)$_REQUEST['l']== 1){ echo "You have been logged in, click <a href=\"tut023.php\">here</a> to go back to the main page."; $_SESSION['isloggedin'] = 1; }else{ if((int)$_SESSION['isloggedin']){ echo "Hey, you're already logged in! click <a href=\"tut023.php\">here</a> to go back to the main page."; }else{ echo "YOU FAIL!"; } } ?>
logout.php
<?php //logout file session_start(); if($_SESSION['isloggedin']){ session_destroy(); echo "Click <a href=\"tut023.php\">here</a> to go back to the main page!"; }else{ echo "Click <a href=\"login.php?l=1\">here</a> to login to logout!"; } ?>
tut023.php
<?php //PHP Tutorial 023 session_start(); if($_SESSION['isloggedin']){ echo "Yes! you are logged in! and click <a href=\"logout.php\">here</a> to logout!"; }else{ echo "Click <a href=\"login.php?l=1\">here</a> to login"; } print_r($_SESSION); ?>