检查是否使用了PHP session_id [英] Check if PHP session_id is in use

查看:74
本文介绍了检查是否使用了PHP session_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a web-app that users can upload certain files and work on them through the web-app interface. I need to store these files for the length of a users session. I am creating a folder for each user using the session_id as the folder name and storing the files in there.

问题:没有任何迹象表明用户离开了我的站点并且会话已停止使用.我需要一个清理脚本,该脚本需要每个文件夹的名称并检查session_id是否仍处于活动状态,以便删除未使用且现在无法访问的文件夹.我该怎么办?

The problem: There is nothing to indicate that a user walked away from my site and the session is going out of use. I need a cleanup script that takes the name of each folder and checks if that session_id is still active in order to delete unused and now unreachable folders. How can I do this?

推荐答案

我遇到了完全相同的问题.我的解决方案是检查会话文件:

I have had precisely the same issue. My solution was to check for the session file:

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

?>

请注意,这假设session.save_handler ini设置被设置为"files"session.save_path设置没有目录级别前缀(即与regex /^\d+;/不匹配),并且php的自动会话垃圾收集已启用.如果以上任一假设都不成立,那么无论如何您都应该执行手动会话垃圾回收,因此可以在其中添加清理代码.

Note that this assumes that the session.save_handler ini setting is set to "files", the session.save_path setting does not have the directory-level prefix (i.e. does not match regex /^\d+;/ ) and that php's automatic session garbage collection is enabled. If either of the above assumptions are not true then you should be implementing manual session garbage collection anyway, so can add your clean-up code to that.

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

This also assumes that the only files in $session_files_dir are your per-session folders and they are all named after their associated session_id.

这篇关于检查是否使用了PHP session_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆