SESSION variables not passed from page after destroying the rest - php

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.

Related

Proper way to logout of webpages

I've been using session_destroy() for a long time to end a user's session. But after diving deep, I realized that it will only destroy the session data at the server side. The cookie will still be stored at the client's side, which means that the browser will continue sending cookies, but with session id which is no longer valid.
So, what is the right way to log out of a session? Does one need to delete the cookie at the client side as well?
According to the manual, there's more to do:
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.
<?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();
?>

Destroying a session if it already exists?

What I am trying to do:
When a user hits the index.php page (the start of a couple pages of forms), I need any existing session to be destroyed and a new one to start. This is so that old session variables are not reused in the new process.
What I have done:
I believe this should check if a session already exists, if it does, destroy it and start a new one. (Need to use session_id() for the check)
if(session_id() == '') {
session_start();
}else{
session_destroy();
session_start();
}
The issue:
The previous session variables are still set and causing issues with the process.
Am I missing something in the way to reset all session varibles?
In documentation you can read:
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. session_destroy();
So you have to do following things:
$_SESSION = array(); //empty session variable
$cookieParams = session_get_cookie_params();
setcookie(
session_name(),
'',
0,
$cookieParams['path'],
$cookieParams['domain'],
$cookieParams['secure'],
$cookieParams['httponly']
);
session_destroy(); //and now you can call your function

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.

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

why is php generating the same session ids everytime in test environment (WAMP)?

i've configured wamp in my system, and am doing the development cum testing in this local environment. i was working on the logout functionality, and happened to notice that the session ids being generated are same within the browser.
Eg - chrome always generates session id = abc, for all users even after logging out and logging in; IE always generates session id = xyz, for all users.
Is this an issue with wamp/ my test environment?
please find below my logout php script -
<?php
session_start();
$sessionid = session_id();
echo $sessionid;
session_unset();
session_destroy();
?>
You probably still have the cookie with the old session ID in it as neither session_unset nor session_destroy deletes that cookie:
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.
So use setcookie to invalidate the session ID cookie after logout:
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
Another recommendation is to regenerate the session ID after successful authentication using session_regenerate_id(true).
Will work. Please try this
session_start();
session_regenerate_id(TRUE);
session_destroy();
You must regenerate the session id using function session_regenerate_id(). Without that, the session ID would be the same between page refreshes.
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.
Taken from http://php.net/manual/en/function.session-destroy.php
session_unset() and session_destroy() do not delete the session cookie. You have to manually unset it with a setcookie() call.
session_unset is the converse of session_register(), and session_destroy simply cleans out $_SESSION without affecting the cookie.
from the 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.
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.
Unless you specifically unset the cookie, then the cookie will still exist and the next time session_start() is called, it will use that as the session id. Closing the browser also should clear the cookie because they are generally set by php to expire on browser close.
To stop session hijacking follow the below code in PHP
session_start();
/* to stop session hijacking */
// Generate new session without destroying the old one
session_regenerate_id(false);
// Fetch current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Assign session ID to the new one, and start it back up again
session_id($newSession);
session_start();

Categories