会话在php中按时到期

时间:2013-10-27 13:09:53

标签: php session

我是Php的新手。我正在开发一个网站,我已经使用会话登录和注销代码。我只是想知道如何在特定时间之后使我的会话到期。例如说20分钟闲置使用。 我的登录代码:

<?php
ob_start();
include("config.php");

session_start();

// set timeout period in seconds
$inactive = 1200;

// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['start'];
    if($session_life > $inactive) {
        session_destroy(); header("Location: logout.php"); 
    }
}

$_SESSION['timeout'] = time();

if($_SERVER["REQUEST_METHOD"] == "POST") {
    $myusername=addslashes($_POST['username']); 
    $mypassword=addslashes($_POST['password']);
    $sql="SELECT rid FROM register WHERE rname='$myusername' and rpass='$mypassword'";
    $result=mysql_query($sql);
    $row=mysql_fetch_array($result);
    @$active=$row['active'];
    $count=mysql_num_rows($result);
    if($count==1) {
        $_SESSION['myusername']=$myusername;
        $_SESSION['login_user']=$myusername;
        echo "<script language=\"javascript\">
        window.location.assign('Home.php')</script>";
    }
    else {
        $error="Your Login Name or Password is invalid";
    }
}
?>
<html>
<head>

<title>Login Page</title>


</head>
<body>    
<div style="margin:30px">    
<form action="" method="post">
<label>UserName  :</label><input type="text" name="username" required="required" class="box"/><br /><br />
<label>Password  :</label><input type="password" name="password" required="required" class="box" /><br/><br />
<input type="submit" value=" Submit "/>&nbsp;&nbsp;<input type="reset" value="Reset"/><br />
<br />
Not a member yet..? &nbsp;&nbsp;  <a href="register.php">Register</a></li>

</form>
<div style="font-size:11px; color:#cc0000; margin-top:10px"><?php echo @$error; ?></div>
</div>
</div>


</body>
</html>

和退出代码:

<?php
session_start();
if(session_destroy()) {
    header("Location: home.php");
}
?>

此代码运行正常,但用户无法登录。

1 个答案:

答案 0 :(得分:1)

你永远不会设置$_SESSION['start']。这一行

$session_life = time() - $_SESSION['start'];

应该是

$session_life = time() - $_SESSION['timeout'];

不应该吗?