How can I expire a user's session in PHP? - php

Some people say use unset($_SESSION["..."]) and some say session_unset() and some say $_SESSION = array() and some say session_destroy() and I am saying "for God's sake, this stuff is getting confusing, can someone please explain me which is the correct/secure way to log the user out" and what is used for what?
Appreciated...

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
RTM

Here is the difference between the entities
you can remove a single variable in the session
unset($_SESSION['shape']);
this would remove all the variables in the session, but not the session itself
session_unset();
this would destroy the session variables
session_destroy();

First of all, session_destroy() is not the same as the other methods. This one will destroy the current session data on the server, but will not unset any of the variables. It's simply the counterpart to session_start().
session_unset() is the deprecated equivalent to doing $_SESSION = array(). The latter and unset($_SESSION["..."]) are different only in the fact that the unset() route will only unset a single session variable, the one named in [...]. Never do unset($_SESSION), as that will interfere with the session mechanism itself.
Old question reference.

The only ones saying session_unset() are the ones stuck on obsolete versions of PHP - the function's been deprecated for a LONG time now.
The exact answer to this question depends on exactly what your code uses to determine if someone is "logged in" v.s. someone who is "logged out".
If you have a single $_SESSION['logged_in'] = true that your code looks for, then why unset it? Just set it to false and boom... user is logged out.

session_destroy ā€” Destroys all data registered to a session
session_unset ā€” Free all session variables
http://www.php.net/manual/en/book.session.php
The most I've seen used is to call them in this order.
session_unset();
session_destroy();
$_SESSION = array();

if you use session_destroy() then the cookie in the browser is also cleard (and probbley a new session gets created later)
personaly i use an object(s) to track different things (like public loggedIn = False; and a function witch actally logs the user in)
session_unset() is handy if you want to keep the coockie, but you will end up with more empty sessions in the server

Related

decision for logout in PHP

I have a website in which I set several variables like
$_SESSION["id"]
$_SESSION["email"]
$_SESSION["role"]
When user clicks on logout should I use session_destroy() or unset all the variables,
it has no special impact on my site, but considering the fact that my sessions are stored on elastic cached with Redis?
I think unless I do session_destroy() the session will not be removed from Redis,(thus occupying memory)
Any help?
Use session_destroy() if you are using it as a logout link, it will get rid of all session data without really having to worry about it. Just remember you have to refresh or redirect because the variables are still set on that page after you use session_destroy
Source: Session unset, or session_destroy?
Depends on if you want to keep any other session data. I only use session_destroy() when I'm positive I want to wipe out the entire user session, otherwise I unset()
You can simply use session_destroy() function. Create a logout.php page and add the following code,
<?php
session_destroy();
header('Location: index.php');
?>
Then call this logout.php by adding links to these page,
Logout
This will destroy your session and re-direct to your index.php page.
Unset will destroy a particular session variable like unset($_SESSION['id']); whereas session_destroy() will destroy all the session data for that user.
I found on the Internet sometimes extended session_destroy, what I use:
function sessionDestroy()
{
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params['path'], $params['domain'],
$params['secure'], $params['httponly']
);
session_destroy();
}

Session taking its own sweet time to be Destroyed

I have created a user page with a menu that contains a logout button. Upon clicking the button, the user is directed to a logout page with the following code:
session_start();
session_destroy();
include("/var/www/include/header.inc");
echo "<h>Logout Success</h>";
include("/var/www/include/menu.inc");
include("/var/www/include/footer.inc");
The code in the menu.inc file is written such that:
if(#$_SESSION['login'] == "yes")
{
// show expanded menu
}
else
{
// show normal menu
}
What I am seeing now after logging out is the expanded menu. It seems that the menu is being included faster than the session can be destroyed, thus creating an impression that the user is still logged in. Is there a way to avoid such a situation?
session_destroy doesn't unset the $_SESSION array, so the rest of the page after session_destroy will still see it. You could simply try this
session_destroy();
unset($_SESSION);
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
Source.
To completely clear all session data you have to use something similar to
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
This is explained in PHP manual:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.

Why is PHP session_destroy() not working?

I tried to destroy all session variable by using the session_destroy() method, but after using this method, the values are not destroyed.
Why is session_destroy() not working?
Is there any other way to destroy the session in PHP?
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
session_destroy();
session_unset();
}
Perhaps is way too late to respond but, make sure your session is initialized before destroying it.
session_start() ;
session_destroy() ;
i.e. you cannot destroy a session in logout.php if you initialized your session in index.php. You must start the session in logout.php before destroying it.
After using session_destroy(), the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION, which was already populated for this request, but it will be empty in future requests.
You can manually clear $_SESSION if you so desire ($_SESSION = [];).
If you need to clear the values of $_SESSION, set the array equal to an empty array:
$_SESSION = array();
Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
I had to also remove session cookies like this:
session_start();
$_SESSION = [];
// If it's desired to kill the session, also
// delete the session cookie.
// Note: This will destroy the session, and
// not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
Source: geeksforgeeks.org
Actually, it works, but you also need to do $_SESSION = array(); after the session_destroy to get rid of $_SESSION variables. However, avoid doing unset($_SESSION) because that makes sessions useless.
Well, this seems a new problem for me, using a new php server. In the past never had an issue with sessions not ending.
In a test of sessions, I setup a session, ran a session count++ and closed the session. Reloaded the page and to my surprise the variable remained.
I tried the following suggestion posted by mc10
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
However, that did not work. I did not think it could work as the session was not active after destroying it, so I reversed it.
$_SESSION = array();
session_destroy();
That worked, reloading the page starting sessios and reviewing the set variables all showed them empty/not-set.
Really not sure why session_destroy() does not work on this PHP Version 5.3.14 server.
Don't really care as long as I know how to clear the sessions.
session_destroy() is effective after the page load is complete. So in the second upload, the session is terminated. But with unset() you can also log out from within the page.
if you destroy the session on 127.0.0.1 it will not affect on localhost and vice versa
It works , but sometimes it doesn't (check the below example)
<?php
session_start();
$_SESSION['name']="shankar";
if(isset($_SESSION['name']))
{
echo $_SESSION['name']; // Outputs shankar
}
session_destroy();
echo $_SESSION['name']; // Still outputs shankar
Weird!! Right ?
How to overcome this ?
In the above scenario , if you replace session_destroy(); with unset($_SESSION['name']); it works as expected.
But i want to destroy all variables not just a single one !
Yeah there is a fix for this too. Just unset the $_SESSION array. [Credits Ivo Pereira]
unset($_SESSION);
Add session_start(); before !Doctype Declaration
<?php session_start(); ?>
<!doctype html>
<html>
<body>
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800))
{
session_destroy();
session_unset();
}
?>
</body>
</html>

SESSION variables not passed from page after destroying the rest

I am at a total loss for words.
I allow an admin to reset their registration if reaching an error during the process. In theory, the following code should function like this:
page is reached, $adminvalidated is set based on session data. The $_SESSION array is cleared; the cookie is cleared on the consumer end; the session id is regnerated and the session is destroyed. Then the session is restarted and the previously mentioned variable is put back into Session.
the "echo" statements included below work but when I redirect to another page (commented out below), the session variables DO NOT carry over.
Yes I have started the session on the follow up page as well.
<?php
session_start();
ob_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
$adminvalidated = $_SESSION['ADMINVALIDATED'];
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_regenerate_id(true);
session_destroy();
session_start();
$_SESSION['ADMINVALIDATED'] = $adminvalidated;
echo $_SESSION['ADMINVALIDATED'];
/*
header("Location: ../a.php");
exit;*/
?>
In general it suffices to call session_regenerate_id(true) to change the session ID of the current session and invalidate the association with the previous session ID.
If you additionally want to clear any session data except $_SESSION['ADMINVALIDATED'], just do this:
session_regenerate_id(true);
$_SESSION = array(
'ADMINVALIDATED' => $_SESSION['ADMINVALIDATED']
);
From the manual page of session_start:
As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.
Just clear your session with session_unset, regenerate the session id and then reset your admin var. No need to destroy then restart the session.
I'm really not sure why you're going through all of these steps. session_regenerate_id() is enough on it's own to regenerate the session token and the associated cookie. The function creates a new session token and creates a new session cookie for you while preserving the values you have in the current session. Since setting a new cookie with the same name overwrites an old one isn't simply calling session_regenerate_id() enough?
Feel free to clarify things if I've missed something.

Truly destroying a PHP Session?

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, Iā€™d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();

Categories