I want a method to force logout all logged in users using Php
the session check code goes like this:
<?php
include "dbConn.php";
session_start();
if (!isset($_SESSION['login_user'])) {
header("location:Login.php");
die();
}
?>
so it depends on the session variable "$_SESSION['login_user']" , So is there a way to unset this variable for all the logged in users ?
Regards
As noted in my comment, you could also just change the session key that you are testing. I would recommend making that globally available and assign it a version number that you increment when you want to log everyone out.
Here's a full version that also includes full destruction of the session's data that you may or may not want. This code hasn't been tested but I'm fairly confident it is mostly accurate.
Also, this doesn't "log everyone out", it instead logs everyone out the next time they access the site. For most people this is the same thing, but it is possible that some site's might have a need for the former, and I think the other comments address that instead.
// This should be in a globally available file, and all
// session checks should rely on this
const SESSION_USER_KEY = 'login_user_v1';
session_start();
if (!isset($_SESSION[SESSION_USER_KEY])) {
// Only needed if you potentially have additional code before the redirect
$_SESSION = [];
// Optionally kill the cookie, see https://www.php.net/manual/en/function.session-destroy.php#example-4744
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
session_destroy()
header("location:Login.php");
die();
}
Related
I have 2 different session id's on 5 different php pages in the same directory on the same host.
I call session_start(); right after the php-tag on top of every page
I converted all the pages to utf-8 without DOM
I set all file permissions to 644
I tried clearing my browser cache
I tried clearing the sessions using the script below
session_start();
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_unset();
// 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();
To no avail.
How do I fix this bug?
If you use unset($_SESSION); that should remove all current sessions I believe.
Then, to set a global session you just do
$_SESSION['user_id'] = "0001"
And then call it by using $_SESSION['user_id'].
Make sure, like you do in the demo above, that you have session_start(); at the top of pages you want to call session variables on.
That might not be the most up to date way, but that's how I've been doing it - just with the unset being assigned to each part of the session array instead of the whole thing.
I am working on a PHP project where in I need to clear the seesion on click browser close.
My project :
Index.php -> userdata.php -> reports.php ->finalreport.html
is it possible to handle session destroy?
I need to clear session , whenever user exits browser while they are in any page.
Please let me know how can we handle this.
the session is destroyed when the user closes the browser**. if you want to destroy it as soon as the user unloads the page, you could add a handler to the page unload event (something like jquery unload) and do a ajax request to a script that just clears the session.
EDIT: per OP's request, i'll add specific code.
1) in all pages (Index.php, userdata.php, reports.php, finalreport.html) add this javascript code
$(window).unload(function() {
$.get('session_destroyer.php');
});
2) in session_destroyer.php use this code (taken from php.net)
<?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();
?>
hope this helps
** NOTE: as one commenter noted, this assumes you're using cookie-based sessions (which is the default in PHP, i think)
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
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.
I'm trying to correctly log out of an admin user. Here is my function:
function logout()
{
$_SESSION = array(); //destroy all of the session variables
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_destroy();
}
Basically, once I authenticate the password, I set the session as being valid (only 1 user total). Now, when the admin hits logout, I want to destroy the current session, and also destroy the cookie, so that they can't just go back to the admin page using the stored session cookie in the browser. but my code doesn't work. i hit logout, and i can just directly navigate back to the admin page. however, if i delete my cookies, the functionality is perfect. so what's wrong with the cookie deleting function here?
If you really want to cover all bases try doing:
setcookie (session_id(), "", time() - 3600);
session_destroy();
session_write_close();
That should prevent further access to the session data for the rest of PHP execution. The browser may still show the cookie being set however the $_SESSION super will be blank
Maybe your problem is not the cookie, but the browser showing a cached version of your admin page. Could that be? If it disappears when you hit F5, it's probably that. This can be sorted by setting the right cache-control headers.
Check out this SO question on the issue of how to set caching. The question is about exactly the other way round (forcing browsers to cache) but you'll figure out what to change to turn caching off.
Just a tip for others who are having issues expiring session cookies:
PHP - why can't I get rid of this session id cookie?
Always use session_get_cookie_params() as in the answer to the question in the link above.