i am having a debate on what would be a better method for loging out in php , if someone could help me clarify i would be most gratefull :
I have two versions of the code for log out
1 )
$logoutGoTo = "login.php";
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['username'] = NULL;
$_SESSION['user_id'] = NULL;
unset($_SESSION['username']);
unset($_SESSION['user_id']);
$_SESSION = array();
if ($logoutGoTo != "") {header("Location: $logoutGoTo");
exit;
2)
session_start();
session_unset();
session_destroy();
Which is the better solution?
Generally neither because they both essentially destroy the entire session.
Sessions aren't just for keeping user's logged in. Sessions are used to track other data which may not be linked to a user's account and so you might not want to destroy it when logging out.
Take this for example, you store the language setting in the session. Now the user logs out, you want to keep language setting but logout the user. If you destroy the session then all other data your tracking is destroyed.
I would simply unset/remove the session variables that are keeping the user logged in.
It depends on your situation. If you hold more data in session then login information it would be not a good idea to unset the whole session. Otherwise the second version seems a bit cleaner.
It depends. If you don't have any other $_SESSION variables you want to keep, and your project has more than one developer, #2 is definitely the better option.
On the other hand, if you either have other $_SESSION variables, or you are developing all by yourself, then you might want to use #1 (you will be able to keep track of all the $_SESSION variables you set and unset, which is a "reminder" for you, but be careful not to forget any variables that you need to unset).