如何杀死一个/所有 php 会话?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5193744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:35:21  来源:igfitidea点击:

How to kill a/all php sessions?

phpsessionlogin

提问by TDSii

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?

如何读取对我的网站进行的所有会话,并销毁部分或所有会话?

回答by Marc B

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 设置进行比较。它实际上并不处理会话数据。

回答by m4rc

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().

回答by TheBlackBenzKid

Updated - Aug 2012

更新 - 2012 年 8 月

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 这样的服务器,您可以关闭、清理缓存、刷卡内存重置、清除日志等,并且通常会删除临时使用情况。甚至降低内存的限制。

回答by KARASZI István

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. Screenshot of Session Occupied by Process and could not delete it

如果您使用 PHP 会话存储,那么它们可能位于您服务器的临时目录中。删除所选文件将“终止”会话。但是,如果您的服务器处于运行状态,则该会话文件可能被 HTTP 进程占用,您将无法删除它。看看下面的图片。以“+~”开头的文件都是会话文件。 Session Occupied by Process 的截图,无法删除

A nicer solution is to use a database session storage and delete the selected sessions from there. You can check out HTTP_Session2which has multiple containers.

更好的解决方案是使用数据库会话存储并从那里删除选定的会话。您可以查看HTTP_Session2哪个有多个容器

回答by Sherif

Clearling allsessions at once would require first knowing which session.save_handleris being used to store sessions and locating the session.save_pathin 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 保存处理程序

$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 客户端请求的带外执行此操作,因为清理大型会话存储可能需要一些时间,并且在正常请求生命周期中会产生无意的副作用。

回答by Nahid Sultan

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
}

?>

回答by Taufik Nurrohman

I will create a txtfile 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 charlieuser to be logged out, simply remove the token file:

因此,如果您想强制charlie退出该用户,只需删除令牌文件:

// Force logout the `charlie` user
unlink('log/token.charlie.txt');

回答by Robin LeBon

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);