如何在 PHP 中设置会话超时代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20235850/
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
How to set session timeout code in PHP
提问by SATSANGI
I have one page session.php and my code is:
我有一页 session.php,我的代码是:
@session_start();
if(!isset($_SESSION['uname']) || $_SESSION['uname'] == " " || !isset($_SESSION['uid']) || $_SESSION['uid'] == " ")
{
echo "<script language='javascript'>";
echo "window.location='../index.php'";
echo "</script> ";
exit;
}
And I also want to edit session timeout function this code is:
而且我还想编辑会话超时函数,这段代码是:
$_SESSION['start'] = time(); // taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (1* 10) ; // ending a session in 30 seconds
$now = time(); // checking the time now when home page starts
if($now > $_SESSION['expire'])
{
session_destroy();
echo "Your session has expire ! <a href='logout.php'>Click Here to Login</a>";
}
else
{
echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
}
But this code is not working so help me how can I set session time out in session.php page.
但是这段代码不起作用,所以帮助我如何在 session.php 页面中设置会话超时。
Thank You..
谢谢你..
回答by Krish R
Can you try this, Because of, in your code you have setting expire time each & every time the page gets load, now added condition.
你能试试这个吗,因为,在你的代码中,你每次和每次页面加载时都设置了过期时间,现在添加了条件。
@session_start();
if(!isset($_SESSION['uname']) || $_SESSION['uname'] == " " || !isset($_SESSION['uid']) || $_SESSION['uid'] == " ")
{
echo "<script language='javascript'>";
echo "window.location='../index.php'";
echo "</script> ";
exit;
}
$_SESSION['start'] = time(); // taking now logged in time
if(!isset($_SESSION['expire'])){
$_SESSION['expire'] = $_SESSION['start'] + (1* 10) ; // ending a session in 30 seconds
}
$now = time(); // checking the time now when home page starts
if($now > $_SESSION['expire'])
{
session_destroy();
echo "Your session has expire ! <a href='logout.php'>Click Here to Login</a>";
}
else
{
echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
}

