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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置