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,
I will create a txt
file containing the token which has the same value as the generated login session as a comparison every time the user is logged in:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$token = sha1(uniqid(mt_rand(), true));
if($everything_is_valid) {
// Set login session
$_SESSION[$_POST['username']] = $token;
// Create token file
file_put_contents('log/token.' . $_POST['username'] . '.txt', $token);
// Just to be safe
chmod('log/token.' . $_POST['username'] . '.txt', 0600);
}
}
Checks for logged in user(s):
if(isset($_SESSION['charlie']) && file_exists('log/token.charlie.txt') && $_SESSION['charlie'] == file_get_contents('log/token.charlie.txt')) {
echo 'You are logged in.';
}
So, if you want to force this charlie
user to be logged out, simply remove the token file:
// Force logout the `charlie` user
unlink('log/token.charlie.txt');
I found this code very helpful and it really worked for me
<?php
$path = session_save_path();
$files = glob($path.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
?>
It depends on your session storage.
If you're using PHP session storage, then they may be in the temporary directory of your server. Deleting the selected files will "kill" the session. However if your server is in running state, that session file may be occupied by HTTP process and you won't be able to delete it. Just look at the image below. File named as starting with "+~" are all session files.
A nicer solution is to use a database session storage and delete the selected sessions from there. You can check out HTTP_Session2 which has multiple containers.