dongtiannai0654 2013-09-05 00:29
浏览 48
已采纳

将时间存储在DB中并在登录PHP后恢复

We already know that the following code in PHP will log the user out after 5 mins of inactivity.

$timeout = 5*60; // Set timeout minutes
$logout_redirect_url = "index.php"; // Set logout URL

if (isset($_SESSION['start_time'])) {
    $elapsed_time = time() - $_SESSION['start_time'];
    if ($elapsed_time >= $timeout) {
        session_unset();
        session_destroy();
        header("Location: $logout_redirect_url");
    }
}
$_SESSION['start_time'] = time();

I want to implement a modification of the current code and do something like this:

  • Assume the user logs out when he had 3 minutes left before automatic logout(assuming the time doesn't restart for him after his inactivity for 2 minutes), we keep track of the time he has left by storing it in a DB (MySQL) and later on start reducing from the same 3 minutes after he logs back in. How can i do this?
  • 写回答

1条回答 默认 最新

  • duanmen8491 2013-09-05 01:27
    关注

    Track by the time used, not the currentTime/storedTime. Just use those to figure out the time remaining. This is a quick example. There may be some small errors and improvements that can be made. It should be plenty to help you implement a solution.

    User visits page:

    if (empty($_SESSION['start_time'])) {
      $_SESSION['start-time'] = time();
    }
    
    $timeLeft = //get time from db
    
    //if there is a value in the db, that is the time left, otherwise, use the max time allowed (new timer)
    $timeLeft = (!empty($timeLeft)) ? $timeLeft : $timeAllowed
    $timePassed = time() - $_SESSION['start_time'];
    if ($timePassed > $timeAllowed) {
      //logout
    }
    

    Then, when the user leaves:

    $timeLeft = $timeAllowed - (time() - $_SESSION['start_time']);
    //Store $timeLeft in the database - should be a value like 180 (3 minutes)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码