I have a very basic php session login script. I want to force logout of a certain user or force logout of all users.
我有一个非常基本的php会话登录脚本。我想强制注销某个用户或强制注销所有用户。
How can I read all sessions made to my website, and destroy some or all sessions?
如何阅读我网站上的所有会话,并销毁部分或全部会话?
8 个解决方案
#1
13
You could try to force PHP to delete all the sessions by doing
您可以尝试强制PHP删除所有会话
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.
这迫使PHP将所有会话视为具有0秒的生命周期,并且100%的概率被清除。
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.
缺点是,当PHP执行清理时,无论哪个不幸的用户首先运行此操作都会得到一个长时间的暂停,特别是如果有很多会话文件需要通过。
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.
PHP的垃圾收集器是不可控制的,因此您无法为其提供诸如“删除除用户X之外的所有会话”之类的参数。它严格查看会话文件中最后修改/最后访问的时间戳,并将其与max_lifetime设置进行比较。它实际上并不处理会话数据。
#2
6
Updated - Aug 2012
This code is based from the official PHP site, and another well written snippet on SO.
此代码基于官方PHP站点,另一个写得很好的SO片段。
<?php
// Finds all server sessions
session_start();
// Stores in Array
$_SESSION = array();
// Swipe via memory
if (ini_get("session.use_cookies")) {
// Prepare and swipe cookies
$params = session_get_cookie_params();
// clear cookies and sessions
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Just in case.. swipe these values too
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
// Completely destroy our server sessions..
session_destroy();
?>
Works well. Servers like NGinx you can turn off, clean cache, swipe memory reset, clear logs etc and generally remove temp usage. Even drop the limits of memory.
效果很好。像NGinx这样的服务器你可以关闭,清理缓存,刷卡内存重置,清除日志等,并通常删除临时使用。甚至降低了记忆的极限。
#3
3
You can use session_save_path()
to find the path where PHP saves the session files, and then delete them using unlink()
.
您可以使用session_save_path()来查找PHP保存会话文件的路径,然后使用unlink()删除它们。
#4
3
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.
如果您正在使用PHP会话存储,那么它们可能位于服务器的临时目录中。删除所选文件将“终止”会话。
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.
一个更好的解决方案是使用数据库会话存储并从那里删除选定的会话。您可以查看具有多个容器的HTTP_Session2。
#5
2
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:
我将创建一个包含令牌的txt文件,该令牌与生成的登录会话具有相同的值,作为每次用户登录时的比较:
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:
因此,如果要强制此charlie用户注销,只需删除令牌文件:
// Force logout the `charlie` user
unlink('log/token.charlie.txt');
#6
2
Clearling all sessions at once would require first knowing which session.save_handler
is being used to store sessions and locating the session.save_path
in order to delete all sessions. For deleting the current session only, refer to the documentation for session_destroy()
.
一次清除所有会话需要首先知道哪个session.save_handler用于存储会话并找到session.save_path以删除所有会话。要仅删除当前会话,请参阅session_destroy()的文档。
Here are some common examples for deleting all sessions using standard file and memcached save handlers:
以下是使用标准文件和memcached存储处理程序删除所有会话的一些常见示例:
Using file save handler
foreach(glob(ini_get("session.save_path") . "/*") as $sessionFile) {
unlink($sessionFile);
}
Using memcached save handler
$memcached = new Memcached;
$memcached->addServers($listOfYourMemcachedSesssionServers);
// Memcached session keys are prefixed with "memc.sess.key." by default
$sessionKeys = preg_grep("@^memc\.sess\.key\.@", $memcached->getAllKeys());
$memcached->deleteMulti($sessionKeys);
Of course, you might want to consider only doing this out of band from your normal HTTP client requests, since cleaning up large session storage may take some time and have inadvertent side effects in a normal request life cycle.
当然,您可能只想考虑从正常的HTTP客户端请求中带外执行此操作,因为清理大型会话存储可能需要一些时间,并且在正常的请求生命周期中会产生无意的副作用。
#7
0
Taufik's answer is the best i could find.
However, you can further modify it
After authenticating the user and creating the session variables, add these lines:
陶菲克的答案是我能找到的最好的答案。但是,您可以进一步修改它在对用户进行身份验证并创建会话变量之后,请添加以下行:
$token = "/sess_" . session_id();
file_put_contents('log/' . $_SESSION['id'] . '.txt', $token);
If you need to force the user to log out during a cronjob or by an admin request:
如果您需要强制用户在cronjob期间或通过管理员请求注销:
$path = session_save_path();
$file = file_get_contents('log/xxx.txt'); // xxx is user's id
$url = $path.$file;
unlink($url);
#8
0
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
}
?>
#1
13
You could try to force PHP to delete all the sessions by doing
您可以尝试强制PHP删除所有会话
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.
这迫使PHP将所有会话视为具有0秒的生命周期,并且100%的概率被清除。
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.
缺点是,当PHP执行清理时,无论哪个不幸的用户首先运行此操作都会得到一个长时间的暂停,特别是如果有很多会话文件需要通过。
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.
PHP的垃圾收集器是不可控制的,因此您无法为其提供诸如“删除除用户X之外的所有会话”之类的参数。它严格查看会话文件中最后修改/最后访问的时间戳,并将其与max_lifetime设置进行比较。它实际上并不处理会话数据。
#2
6
Updated - Aug 2012
This code is based from the official PHP site, and another well written snippet on SO.
此代码基于官方PHP站点,另一个写得很好的SO片段。
<?php
// Finds all server sessions
session_start();
// Stores in Array
$_SESSION = array();
// Swipe via memory
if (ini_get("session.use_cookies")) {
// Prepare and swipe cookies
$params = session_get_cookie_params();
// clear cookies and sessions
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Just in case.. swipe these values too
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
// Completely destroy our server sessions..
session_destroy();
?>
Works well. Servers like NGinx you can turn off, clean cache, swipe memory reset, clear logs etc and generally remove temp usage. Even drop the limits of memory.
效果很好。像NGinx这样的服务器你可以关闭,清理缓存,刷卡内存重置,清除日志等,并通常删除临时使用。甚至降低了记忆的极限。
#3
3
You can use session_save_path()
to find the path where PHP saves the session files, and then delete them using unlink()
.
您可以使用session_save_path()来查找PHP保存会话文件的路径,然后使用unlink()删除它们。
#4
3
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.
如果您正在使用PHP会话存储,那么它们可能位于服务器的临时目录中。删除所选文件将“终止”会话。
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.
一个更好的解决方案是使用数据库会话存储并从那里删除选定的会话。您可以查看具有多个容器的HTTP_Session2。
#5
2
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:
我将创建一个包含令牌的txt文件,该令牌与生成的登录会话具有相同的值,作为每次用户登录时的比较:
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:
因此,如果要强制此charlie用户注销,只需删除令牌文件:
// Force logout the `charlie` user
unlink('log/token.charlie.txt');
#6
2
Clearling all sessions at once would require first knowing which session.save_handler
is being used to store sessions and locating the session.save_path
in order to delete all sessions. For deleting the current session only, refer to the documentation for session_destroy()
.
一次清除所有会话需要首先知道哪个session.save_handler用于存储会话并找到session.save_path以删除所有会话。要仅删除当前会话,请参阅session_destroy()的文档。
Here are some common examples for deleting all sessions using standard file and memcached save handlers:
以下是使用标准文件和memcached存储处理程序删除所有会话的一些常见示例:
Using file save handler
foreach(glob(ini_get("session.save_path") . "/*") as $sessionFile) {
unlink($sessionFile);
}
Using memcached save handler
$memcached = new Memcached;
$memcached->addServers($listOfYourMemcachedSesssionServers);
// Memcached session keys are prefixed with "memc.sess.key." by default
$sessionKeys = preg_grep("@^memc\.sess\.key\.@", $memcached->getAllKeys());
$memcached->deleteMulti($sessionKeys);
Of course, you might want to consider only doing this out of band from your normal HTTP client requests, since cleaning up large session storage may take some time and have inadvertent side effects in a normal request life cycle.
当然,您可能只想考虑从正常的HTTP客户端请求中带外执行此操作,因为清理大型会话存储可能需要一些时间,并且在正常的请求生命周期中会产生无意的副作用。
#7
0
Taufik's answer is the best i could find.
However, you can further modify it
After authenticating the user and creating the session variables, add these lines:
陶菲克的答案是我能找到的最好的答案。但是,您可以进一步修改它在对用户进行身份验证并创建会话变量之后,请添加以下行:
$token = "/sess_" . session_id();
file_put_contents('log/' . $_SESSION['id'] . '.txt', $token);
If you need to force the user to log out during a cronjob or by an admin request:
如果您需要强制用户在cronjob期间或通过管理员请求注销:
$path = session_save_path();
$file = file_get_contents('log/xxx.txt'); // xxx is user's id
$url = $path.$file;
unlink($url);
#8
0
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
}
?>