增加php会话时间 [英] Increase php session time

查看:45
本文介绍了增加php会话时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 php 会话时间增加到 6 小时.

I am trying to increase my php session time to 6 hours.

这是增加会话时间的代码:

Here is the code to increase the session time:

ini_set('session.gc_maxlifetime', 60 * 60 * 6); // 6 Hours 

然而,它似乎只有 1 小时的会话时间.

However, it seems to ONLY have a session time of 1 hour.

非常感谢任何建议.

此外,我如何测试此功能而不必等待 6 个小时来查看我的会话是否超时.

Also, how do I test this feature without having to wait 6 hours to see if my session times out.

推荐答案

场景

您运行的是 Debian Linux 或 Ubuntu Linux.您希望 PHP 会话持续时间长于默认的 1440 秒(24 分钟).所以你这样做:

You’re running Debian Linux or Ubuntu Linux. You want PHP sessions to last longer than the default 1440 seconds (24 minutes). So you do this:

ini_set('session.gc_maxlifetime', 10800);    # 3 hours

使用此设置,只要用户不关闭浏览器,会话就应保持活动至少三个小时.1

With this setting, sessions should remain active for at least three hours, as long as users don’t close their browser.1

但无论您做什么,会话都会在 24-54 分钟后不断被删除.PHP 似乎忽略了 gc_maxlifetime 设置.

But no matter what you do, sessions keep getting deleted after 24–54 minutes. It seems PHP is ignoring the gc_maxlifetime setting.

为什么会这样

Debian 和 Ubuntu Linux 会覆盖 PHP 的会话行为.如果仔细观察,您会看到 session.gc_probability 设置为 0,这意味着 PHP 的垃圾收集将永远不会运行.相反,/etc/cron.d/php5 中有一个 Debian 特定的 cron 作业,每 30 分钟运行一次!

Debian and Ubuntu Linux override PHP’s session behavior. If you look closely, you’ll see that session.gc_probability is set to 0, meaning PHP’s garbage collection will never run. Instead, there’s a Debian-specific cron job in /etc/cron.d/php5 that runs every 30 minutes!

cron 作业根据 php.ini 中的全局 session.gc_maxlifetime 进行垃圾收集.您应用中的 session.gc_maxlifetime 将被忽略.

The cron job does garbage collection based on the global session.gc_maxlifetime in php.ini. The session.gc_maxlifetime in your app is ignored.

解决方案

虽然您可以禁用 cron 作业和/或修改 php.ini,但我更愿意在不修改系统默认值的情况下解决问题.更好的解决方案是创建您自己的会话目录,在正常目录之外的某个地方,然后在本地启用 PHP 的会话垃圾收集.

While you could disable the cron job and/or modify php.ini, I’d prefer to fix the problem without modifying system defaults. A better solution is to create your own sessions directory, somewhere outside the normal one, and then locally enable PHP’s session garbage collection.

为此设置 session.gc_maxlifetime、session.gc_probability、session.gc_divisor 和 session.save_path:

# Session lifetime of 3 hours
ini_set('session.gc_maxlifetime', 10800);

# Enable session garbage collection with a 1% chance of
# running on each session_start()
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

# Our own session save path; it must be outside the
# default system save path so Debian's cron job doesn't
# try to clean it up. The web server daemon must have
# read/write permissions to this directory.
session_save_path(APP_PARENT_DIR . '/sessions');

# Start the session
session_start();

这篇关于增加php会话时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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