Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a/all php sessions?

Tags:

php

session

login

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?

like image 238
TDSii Avatar asked Mar 04 '11 12:03

TDSii


People also ask

How do I destroy 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.

How can I get all sessions in PHP?

php session_start(); echo "<h3> PHP List All Session Variables</h3>"; foreach ($_SESSION as $key=>$val) echo $key." ".

Which function is use to unset all sessions?

session_unset just remove all session variables.

How can destroy session after some time in PHP?

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.


2 Answers

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.

like image 63
Marc B Avatar answered Sep 28 '22 04:09

Marc B


You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().

like image 44
m4rc Avatar answered Sep 28 '22 06:09

m4rc