php 10分钟过期,如何在30分钟后过期PHP会话?

您应该实现自己的会话超时。其他人(

session.gc_maxlifetime和

session.cookie_lifetime)提到的两个选项都不可靠。我会解释一下原因。

第一:

session.gc_maxlifetime

session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.

但是垃圾收集器只是以session.gc_probability除以session.gc_divisor的概率开始。使用这些选项的默认值(分别为1和100),机会只有1%。

嗯,你可以简单地调整这些值,以便垃圾收集器更频繁地启动。但是当垃圾收集器启动时,它将检查每个注册会话的有效性。这是成本密集型。

此外,当使用PHP的默认session.save_handler文件时,会话数据存储在session.save_path中指定的路径中的文件中。使用该会话处理程序,会话数据的时间将根据文件的最后修改日期而不是最后访问日期计算:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won’t have problems with filesystems where atime tracking is not available.

因此,另外可能发生会话数据文件被删除,而会话本身仍被认为是有效的,因为会话数据最近未被更新。

第二:

session.cookie_lifetime

session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

恩,那就对了。这只会影响Cookie生命周期,会话本身仍然有效。但是服务器的任务是使会话无效,而不是客户端。所以这不帮助什么。事实上,将session.cookie_lifetime设置为0将使会话的cookie成为一个真正的session cookie,只有在浏览器关闭后才有效。

结论/最佳解决方案:

最好的解决方案是实现自己的会话超时。使用一个简单的时间戳,表示最后一个活动(即请求)的时间,并更新每个请求:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {

// last request was more than 30 minutes ago

session_unset(); // unset $_SESSION variable for the run-time

session_destroy(); // destroy session data in storage

}

$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

每次请求更新会话数据也会更改会话文件的修改日期,以使会话不会被垃圾回收器过早删除。

您还可以使用附加的时间戳定期重新生成会话ID,以避免对会话的攻击,如session fixation:

if (!isset($_SESSION['CREATED'])) {

$_SESSION['CREATED'] = time();

} else if (time() - $_SESSION['CREATED'] > 1800) {

// session started more than 30 minutes ago

session_regenerate_id(true); // change session ID for the current session and invalidate old session ID

$_SESSION['CREATED'] = time(); // update creation time

}

笔记:

> session.gc_maxlifetime应该至少等于此自定义到期处理程序(在此示例中为1800)的生命周期;>如果您想要在活动30分钟后而不是在开始后30分钟后过期会话,您还需要使用setcookie和时间()60 * 30到期,以保持会话cookie活动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值