关于How do I expire a PHP session after 30 minutes?,我从第二个答案中复制了一些代码 30分钟内PHP会话到期的简单方法。我想将登录和信息组合到1页和另一页页面是logout.php 这是我的代码。
homepage.php
if(isset($_POST["submitform"])){
$v1 = "admin";
$v2 = "admin";
$v3 = $_POST['username'];
$v4 = $_POST['password'];
if($v1 == $v3 && $v2 == $v4){
session_start();
$_SESSION['username'] = $v1;
$_SESSION['start'] = time(); // taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (1* 30) ; // ending a session in 30 seconds
if(!isset($_SESSION['username'])){
echo "Please Login again <a href='logout.php'>Click Here to Login</a>";
}else{
$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>";
}
}
}else{
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
echo '<font color="red">wrong password</font>"';
}
}else{
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
}
?>
Logout.php
<?php
session_start();
session_destroy();
header('Location: homepage.php');
?>
我将会话过期设置为30秒,但我发现会话未按预期过期。会议永不过期。我想知道我是否将session_start();
放在正确的地方?感谢
答案 0 :(得分:1)
您只是在表单上检查会话的状态。
如果您刷新页面,它将重新发送帖子,登录并延长会话。
你的逻辑必须是:
如果发布,请检查密码并延长会话。
检查会话是否已过期(如果在此处发布,则必须发生这种情况,没有任何区别。)
根据会话检查结果显示登录表单或注销消息。
if (isset($_POST["submitform"])) {
$v1 = "admin";
$v2 = "admin";
$v3 = $_POST['username'];
$v4 = $_POST['password'];
if ($v1 == $v3 && $v2 == $v4) {
session_start();
$_SESSION['username'] = $v1;
$_SESSION['start'] = time();
// taking now logged in time
$_SESSION['expire'] = $_SESSION['start'] + (1 * 30);
// ending a session in 30 seconds
} else {
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
echo '<font color="red">wrong password</font>"';
die();
}
if (!isset($_SESSION['username'])) {
echo "Please Login";
echo '
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit" name="submitform">Sign in</button>
</form>';
} else {
$now = time();
// checking the time now when home page starts
if ($now > $_SESSION['expire']) {
session_destroy();
echo "Your session has expired ! <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>";
}
}
答案 1 :(得分:0)
session_start()
需要成为第一行代码。
此外,您可以将Cookie设置为过期。
答案 2 :(得分:0)
是否可以在同一页面上拥有不同的会话?
YES
所以使用
一个用户,一个会话。周期。
http://us3.php.net/manual/en/ref.session.php