PHP会话生存期问题 [英] PHP session lifetime problem

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

问题描述

我在这里使用PHP5.我已经建立了一个登录系统,可以对照数据库中的记录检查用户名和密码.我想使用会话来存储记录的值.例如,当我到达用户成功登录"的区域时:

I'm using PHP5 here. I have made a login system that check's the username and password against the records in the database. I want to use sessions to store the logged value. For example, when I reach the zone where I "log in" the user succesfully:

if($errors = 0) {
    $_SESSION['logged'] = "1";
}

问题是我希望$_SESSION['logged']保持活动状态持续5分钟,所以当我在这段时间之后执行if($_SESSION['logged'] == "1")时,返回false.另外,我想在用户关闭浏览器后删除此会话.基本上,我需要一个会话配置,以便用户可以安全地离开办公桌,并且当他或某人在10分钟后按下刷新或在关闭浏览器后再次进入时,该会话已被删除,并且访问受到限制.

The problem is that I want the $_SESSION['logged'] to stay active for let's say 5 minutes so when I do a if($_SESSION['logged'] == "1") after this time to return false. Also, I would like to delete this session after the user closes the browser. Basically, I want a session configuration so that the user can safely leave his desk and when him or somebody presses refresh after 10 minutes or enters again after the browser has been closed, the session to be already removed, and the access to be restricted.

有人可以帮忙吗?谢谢.

Can anybody help? Thanks.

推荐答案

使用 session_set_cookie_params() 更改会话cookie的生存期.请注意,默认情况下,它设置为 0 ,这意味着将设置cookie,直到用户退出浏览器为止.您可以通过以下方式执行此操作:

Use session_set_cookie_params() to change the lifetime of the session cookie. Note that by default, it is set to 0 which means that the cookie is set until the user exits the browser. You can do this in the following way:

/* Set to 0 if you want the session
   cookie to be set until the user closes
   the browser. Use time() + seconds
   otherwise. */

session_set_cookie_params(0);
session_start();

然后检查上一次活动时间,每次有人访问页面时都会更新.

Then check for the last activity time, updated each time someone visits a page.

if(($_SESSION['lastActivity'] + 300) < time()) {
    // timeout, destroy the session.
    session_destroy();
    unset($_SESSION);
    die('Timeout!');
} else {
    $_SESSION['lastActivity'] = time();
}

这篇关于PHP会话生存期问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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