检查PHP session_id是否正在使用中

Bar*_*uch 6 php sessionid

我正在构建一个Web应用程序,用户可以通过Web应用程序界面上传某些文件并对其进行处理.我需要将这些文件存储为用户会话的长度.我正在为每个用户创建一个文件夹,使用session_id 文件夹名称并将文件存储在那里.

问题:没有任何迹象表明用户离开了我的网站,会话就不再使用了.我需要一个清理脚本,它取每个文件夹的名称并检查它session_id是否仍处于活动状态,以便删除未使用的和现在无法访问的文件夹.我怎样才能做到这一点?

meg*_*lop 7

我有同样的问题.我的解决方案是检查会话文件:

<?php
// clean-up script.  Get cron/windows task scheduler to run this every hour or so

// this is the path where PHP saves session files
$session_path = ini_get('session.save_path');

// this is the directory where you have created your folders that named after the session_id:
$session_files_dir = '/path/to/your/save/dir';

// loop through all sub-directories in the above folder to get all session ids with saved files:

if ($handle = opendir($session_files_dir)) {

    while (false !== ($file = readdir($handle))) {

        // ignore the pseudo-entries:
        if ($file != '.' && $file != '..') {

            // check whether php has cleaned up the session file
            if (  file_exists("$session_path/sess_$file")  ) {
                // session is still alive
            } else {
                // session has expired
                // do your own garbage collection here
            }

        }
    }

    closedir($handle);
}

?>
Run Code Online (Sandbox Code Playgroud)

请注意,这假设session.save_handlerini设置设置为"files",该session.save_path设置没有目录级前缀(即与正则表达式不匹配/^\d+;/),并且启用了php的自动会话垃圾回收.如果上述任何一个假设都不正确,那么你应该实现手动会话垃圾收集,所以可以添加你的清理代码.

这也假定其中的唯一文件$session_files_dir是每个会话文件夹,并且它们都以其关联的session_id命名.