I have a very basic php session login script. I want to force logout of a certain user or force logout of all users.
How can I read all sessions made to my website, and destroy some or all sessions?
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. Note: You do not have to call session_destroy() from usual code.
php session_start(); echo "<h3> PHP List All Session Variables</h3>"; foreach ($_SESSION as $key=>$val) echo $key." ".
session_unset just remove all session variables.
It can be done by clicking on the logout button or by destroying that session after a fixed time. By default the expiry time of any particular session that is created is 1440 secs i.e. (24*60) i.e. 24 minutes. But in some cases, we need to change the default time accordingly.
You could try to force PHP to delete all the sessions by doing
ini_set('session.gc_max_lifetime', 0); ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 1);
That forces PHP to treat all sessions as having a 0-second lifetime, and a 100% probability of getting cleaned up.
The drawback is that whichever unlucky user runs this first will get a long pause while PHP does cleanup, especially if there's a lot of session files to go through.
For one particular user, you'd have to add some code to your session handler:
if ($_SESSION['username'] == 'user to delete') { session_destroy(); }
PHP's garbage collector isn't controllable, so you can't give it parameters such as "delete all sessions except for user X's". It looks strictly at the last-modified/last-accessed timestamps on the session files and compares that to the max_lifetime setting. It doesn't actually process the session data.
You can use session_save_path()
to find the path where PHP saves the session files, and then delete them using unlink()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With