php 由于不活动导致的会话超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15595913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
session timeout due to inactivity
提问by surfine
I have created a script login.phpand there I have created a session variable named logged_in
我创建了一个脚本,login.php并在那里创建了一个名为的会话变量logged_in
$_SESSION['logged_in'] = true;
I am unable to figure out a way to redirect to redirect to my logout.php after session expires due to inactivity. Also should I put the code that expire this session variable. I have Googled the bug and what it suggest is to tweak php.inifile in most of the articles. However I came across an article saying that it is not the best practice.
I found the following code on StackOverflow, yet I have no idea where to put it:-
由于不活动,会话过期后,我无法找到重定向到我的 logout.php 的方法。我也应该把使这个会话变量过期的代码。我在谷歌上搜索了这个错误,它建议php.ini在大多数文章中调整文件。但是我看到一篇文章说这不是最佳实践。
我在 StackOverflow 上找到了以下代码,但我不知道把它放在哪里:-
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
I would like to know the best way to redirect after session expire and suggestions for where to put the code.
Edit: I forgot to mention that I want to know how to manually set a time for the session to expire.
Thank you in advance
我想知道在会话过期后重定向的最佳方式以及代码放置位置的建议。
编辑:我忘了提到我想知道如何手动设置会话到期的时间。
先感谢您
回答by tomsmeding
If you want to logout the user if they try to load a page when they've been inactive for too long, you should put this code at the top of every php file (before ANY other html tags):
如果您想在用户长时间处于非活动状态时尝试加载页面时将其注销,您应该将此代码放在每个 php 文件的顶部(在任何其他 html 标签之前):
if( $_SESSION['last_activity'] < time()-$_SESSION['expire_time'] ) { //have we expired?
//redirect to logout.php
header('Location: http://yoursite.com/logout.php'); //change yoursite.com to the name of you site!!
} else{ //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
}
Also, put this code at the top of the page where you land when you've successfully logged in:
此外,将此代码放在您成功登录后登陆的页面顶部:
$_SESSION['logged_in'] = true; //set you've logged in
$_SESSION['last_activity'] = time(); //your last activity was now, having logged in.
$_SESSION['expire_time'] = 3*60*60; //expire time in seconds: three hours (you must change this)
On that page you don't have to include the checking code I gave you first.
在该页面上,您不必包含我首先给您的检查代码。
By the way, don't forget to add <?phptags correctly!
顺便说一句,不要忘记<?php正确添加标签!
回答by surfine
Implement this idea:
实现这个想法:
$expire_time = 3*60*60; //expire time
if( $_SESSION['last_activity'] < time()-$expire_time ) {
echo 'session expired';
die();
}
else {
$_SESSION['last_activity'] = time(); // you have to add this line when logged in also;
echo 'you are uptodate';
}

