0

我是 Php 的新手。我正在开发一个网站,并且我已经使用 session 来登录和注销代码。我只是想知道如何在特定时间后使我的 session 过期。比如说 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");
}
?>

此代码运行良好,但用户无法登录。

4

1 回答 1

1

你永远不会设置$_SESSION['start']。这条线

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

应该是

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

不应该吗?

于 2013-10-27T13:18:11.563 回答