Why is PHP session_destroy() not working? - php

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>

Related

getting session variable even after session destroy

I am newbie in php. I can not under stand a thing that session variable is outputting even after session_destroy() and session_unset().Here is my simple code for test
`session_start();
SESSION['name']='sovon';
session_destroy();
session_unset($_SESSION['name']);
echo $_SESSION['name'];
`
The output is 'sovon'. My question what is session_destroy() and session_unset() doing here and whats the difference between them?
Oh! when I am deleting session_destroy() that variable is getting unset. why?
I got it faisal, session_distroy is destroying session if its created in other pages. If the session variable created on the same page then it will be remain. The best practice is to null the session variable after session distroY $_SESSION = NULL;
Like I am using in logout,
session_start();
session_distory();
$_SESSION = NULL;
header('Location: Login.php');
I think this help you.
Perhaps its easier if you read the php manual.
session_destroy()
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.
So if you want to unset the data inside. You have to unset it.
unset($_SESSION);
Session unset...
session_unset()
deletes all variables and leave session_id. But session_unset has no parameters.
What you search is
unset($_SESSION['name']);
The following works perfectly in all browsers to kill and destroy and unset all session info. Perfect to put it in sign-out file.
<?php
session_start();
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>

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();
}

Preserving a Session Variable after session_destroy()?

I'm aware there is an identical question here, but the accepted answer says it is a bug with a patch, yet the link says otherwise. The link says it is intended behaviour and not a bug.
The other answers in the question are exactly what I tried to do.
$variableToPreserve = $_SESSION['foo'];
session_destroy();
session_start();
// At this point in the debugger, all previous session variables are still
// in the session anyway, making me think the session has not been destroyed yet.
$_SESSION['foo'] = $variableToPreserve;
Next request:
session_start();
// This line errors as 'foo' is not in the session.
$var = $_SESSION['foo'];
My only guess is that the session does not actually get destroyed until after that request has completed. The only way I can get it to preserve is by keeping all the session variables but really I need to destroy the session and only have 'foo' set.
Session are handeled via cookies - so (I guess) this should be the expected behaviour.
You could unset all values in the session variable manually:
foreach ($_SESSION as $k => $v) {
unset($_SESSION[$k]);
}
instead for calling:
session_destroy();
session_start();
This would effectivly clear the session for you.
I checked out the code for you, and this is the behavior that I see.
session_start();
$_SESSION['foo'] = 1;
$variableToPreserve = $_SESSION['foo'];
session_destroy();
session_start();
// At this point, the session variable is indeed destroyed, as is evident from the error that the next line throws.
echo $_SESSION['foo'];
$_SESSION['foo'] = $variableToPreserve;
echo $_SESSION['foo'];
// The above line echoes 1
Your code for session destroy is not like the one that provided by PHP Manual, for example:
http://php.net/manual/en/function.session-destroy.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();
YOU CAN TEST A DEMO: http://phpfiddle.org/lite/code/2vi-r9a

How can I expire a user's session in 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

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