douduan6731 2013-06-18 13:56 采纳率: 0%
浏览 43

不活动和登录系统PHP

I am trying to create a system where, when the user is inactive for x amount of time, they should are logged out and sent back to 'index.php'. I am using the code I found here - http://cookbooks.adobe.com/post_Set_a_time_limit_on_a_login_session__PHP_-16701.html and I put it in a function like this:

phpfunc/inactivity.php

<?php

function inactivity() {
    // create a session 
    if (!isset($_SESSION)) {
        session_start();
    }

    // store the current time
    $now = time();

    // get the time the session should have expired
    $limit = $now - 60*20;

    // check the time of the last activity
    if (isset ($_SESSION['last_activity']) && $_SESSION['last_activity'] < $limit) {
        // if too old, clear the session array and redirect
        $_SESSION = array();
        header('../index.php');
        exit;
    } 
    else {
        // otherwise, set the value to the current time
        $_SESSION['last_activity'] = $now;
    }
}

?>

Then, I call the function like this...at the top of my protected page

templates/login_success.php:

<?php
require('/Users/Eamon/Sites/phpfunc/inactivity.php');
inactivity();

if($_SESSION['username'] === null){
    header("location: ../index.php");
}
?>

<h1>Login Successful</h1>
<h2>Username: <? echo $_SESSION['username']?></h2>
<div id="logoutlinkdiv" >
    <a href = "#" >Log out</a>
</div>

I can login - and all the inactivity stuff seems to work. I tested it by adding a few echo statements here and there...and after login I tried going to the protected page - like this "localhost/~Eamon/templates/login_success.php" and it lets me see it...after 20 minutes I have to sign in again. However, I have a page that loads once the user logs out (after clicking the "logoutlinkdiv" link) - and it has a link on it to log in again. When I click this link, I get the message "Wrong Username or Password" - which can be found in the below file (which gets executed upon login). After 20 more minutes, I can login again without getting this error.

checklogin.php

<?php

session_start();

$host="localhost"; // Host name
$username="root"; // Mysql username
$password="bonjour3"; // Mysql password
$db_name="itit"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
$mysqli = new mysqli("$host", "$username", "$password", "$db_name")or die("cannot connect");

// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

$sql = $mysqli->prepare("SELECT * FROM $tbl_name WHERE username=? and password=?");
$sql->bind_param('ss',$myusername,$mypassword);
$sql->execute();
$sql->store_result();//apply to prepare statement
$numRows = $sql->num_rows;

if($numRows === 1){
    $_SESSION['username'] = $myusername;
}
else {
    echo "Wrong Username or Password";
    session_destroy();
}
?>

Here is the aforementioned logout page (where the user can login again...the trouble page!):

templates/logout.php

<?php
session_start();
session_destroy();
?>

<div id="loginlinkdiv" >
    <h2>You have been logged out.</h2>
    <a href = "#">Log in</a>
</div>

In case it is relevant...here is the jquery I am using. I am making an SPA - so jquery is loading and emptying things for me in the "main" div on index.php - here:

index.php

<?php session_start(); ?>

<!DOCTYPE html>
<html>
<head>
<title>it IT</title>
    <script src="reqscripts/jquery.js" type="text/javascript"></script>
    <script src="js/application.js" type="text/javascript"></script>
</head>
<body>
    <div id="main"></div>
</body>
</html>

UPDATE

Following the suggestion - I tried the first answer on this page:

How do I expire a PHP session after 30 minutes?

I changed two files.

phpfunc/inactivity.php now looks like this:

<?php

function inactivity() {

    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
        // last request was more than 30 minutes ago
        session_unset();     // unset $_SESSION variable for the run-time 
        session_destroy();   // destroy session data in storage
        header("/Users/Eamon/Sites/index.php");
    }

    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
}

?>

and templates/login_success.php looks like this:

<?php
require('/Users/Eamon/Sites/phpfunc/inactivity.php');
session_start();
inactivity();
?>

<h1>Login Successful</h1>
<h2>Username: <? echo $_SESSION['username']?></h2>
<div id="logoutlinkdiv" >
    <a href = "#" >Log out</a>
</div>

Still the same problem appears to be happening...and I think I caught a new glitch. When I click the login link (templates/logout.php) it brings me to index.php. I try to login, but the information in the textboxes gets reset, and seemingly nothin happens. When I try again - I get "Wrong Username or Password" again. Also - <? echo $_SESSION['username']?> is not showing up on the login_success.php page anymore.

UPDATE

It seems as if I'm not getting signed in because <? echo $_SESSION['username']?> still doesnt output anything.

  • 写回答

1条回答 默认 最新

  • dongzi1397 2013-06-18 14:39
    关注

    Option one:

    use session.gc_maxlifetime

    ini_set('session.cookie_lifetime',  600);
    session_start();
    

    http://php.net/manual/en/function.session-set-cookie-params.php

    This value (default 1440 seconds) defines how long an unused PHP session will be kept alive. For example: A user logs in, browses through your application or web site, for hours, for days. No problem. As long as the time between his clicks never exceed 1440 seconds. It's a timeout value.

    option two:

    session.cookie_lifetime

    This value (default 0, which means until the browser's next restart) defines how long (in seconds) a session cookie will live. Sounds similar to session.gc_maxlifetime, but it's a completely different approach. This value indirectly defines the "absolute" maximum lifetime of a session, whether the user is active or not. If this value is set to 60, every session ends after an hour a minute.

    Option Three:

    session_start();
    // set time-out period (in seconds)
    $inactive = 600;
    
    // check to see if $_SESSION["timeout"] is set
    if (isset($_SESSION["timeout"])) {
        // calculate the session's "time to live"
        $sessionTTL = time() - $_SESSION["timeout"];
    
        if ($sessionTTL > $inactive) {
            session_destroy();
            header("Location: /logout.php");
        }
    }
    
    $_SESSION["timeout"] = time();
    
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大