PHP 中的会话超时:最佳实践 [英] Session timeouts in PHP: best practices

查看:36
本文介绍了PHP 中的会话超时:最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

session.gc_maxlifetimesession_cache_expire() 之间的实际区别是什么?

What is the actual difference between session.gc_maxlifetime and session_cache_expire() ?

假设我希望用户会话在 15 分钟非活动(而不是首次打开后 15 分钟)后无效.其中哪一项会帮助我?

Suppose I want the users session to be invalid after 15 minutes of non-activity (and not 15 after it was first opened). Which one of these will help me there?

我也知道我可以做 session_set_cookie_params() 它可以将用户的 cookie 设置为在一段时间内过期.但是,cookie的过期时间和服务端的实际会话过期时间是不一样的;当 cookie 过期时,这是否也会删除会话?

I also know I can do session_set_cookie_params() which can set the user's cookie to expire in some amount of time. However, the cookie expiring and the actual session expiring on the server side are not the same; does this also delete the session when the cookie has expired?

我的另一个解决方案很简单$_SESSION['last_time'] = time()在每个请求上,并将会话与当前时间进行比较,然后根据该时间删除会话.不过,我希望有一种更内置"的机制来处理这个问题.

Another solution I have though of is simple $_SESSION['last_time'] = time() on every request, and comparing the session to the current time, deleting the session based on that. I was hoping there was a more "built-in" mechanism for handling this though.

谢谢.

推荐答案

每次 session_start 被称为会话文件时间戳(如果存在)被更新,用于计算是否超过 session.gc_maxlifetime.

Each time session_start is called the session files timestamp (if it exists) gets updated, which is used to calculated if session.gc_maxlifetime has been exceeded.

更重要的是,在超过 session.gc_maxlifetime 时间后,您不能依赖会话过期.

More importantly you can't depend on a session to expire after session.gc_maxlifetime time has been exceeded.

PHP 在加载当前会话后使用 session.gc_probabilitysession.gc_divisor 它计算垃圾收集运行的概率.默认情况下,它的概率为 1%.

PHP runs garbage collection on expired sessions after the current session is loaded and by using session.gc_probability and session.gc_divisor it calculates the probability that garbage collection will run. By default its a 1% probability.

如果您的访问者数量较少,则不活动的用户可能会访问本应已过期并被删除的会话.如果这对您很重要,您将需要在会话中存储时间戳并计算用户处于非活动状态的日志.

If you have a low number of visitors there is a probability that an inactive user could access a session that should have expired and been deleted. If this is important to you will need to store a timestamp in the session and calculate how log a user has been inactive.

此示例替换了 session_start 并强制执行超时:

This example replaces session_start and enforces a timeout:

function my_session_start($timeout = 1440) {
    ini_set('session.gc_maxlifetime', $timeout);
    session_start();

    if (isset($_SESSION['timeout_idle']) && $_SESSION['timeout_idle'] < time()) {
        session_destroy();
        session_start();
        session_regenerate_id();
        $_SESSION = array();
    }

    $_SESSION['timeout_idle'] = time() + $timeout;
}

这篇关于PHP 中的会话超时:最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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