Raheem
Raheem

Reputation: 25

Timeout Session When There's No Activity From the User

how can I timeout a session when there is no activity from the user? Here is my code which has the name session.php:

<?php
  require_once('conn.php');
  session_start();

  $user_check = $_SESSION['login_user'];

  $ses_sql = mysqli_query($conn, "select * from employee where Username = '$user_check'");

  $row = mysqli_fetch_array($ses_sql, MYSQLI_ASSOC);

  $login_session = $row['EmployeeName'];

  if (!isset($_SESSION['login_user'])) {
      header("location:index.php");
  }
?>

Upvotes: 1

Views: 161

Answers (1)

Buwaneka Sudheera
Buwaneka Sudheera

Reputation: 1417

Include this code into the profile page you want to redirect to after logged in. First calculate the time like this.

<script>
var sec = 0;
var min = 0;
var hrs = 0;

function time () {

    if (sec<=59) {
        sec++;
        if (sec<10) {
        sec="0"+sec;
        }
        if (sec>59) {
            sec=0;
            min++;

            if (min>59) {
                min=0;
                hrs++;

                if (hrs>24) {
                    hrs=0;
                };
            };
        };

    };


    document.getElementById("time").innerHTML=hrs+":"+min+":"+sec;

}
function tick () {
    if (min<10) {
        min="0"+min;
        }

    if (hrs<10) {
        hrs="0"+hrs;
    }
}
window.onload=function () {
    tick();
    setInterval(time,1000);
}

</script>

This will give you a time. After that do this. Let's assume you want to time it out in 30 seconds. Here login.php is any common page which redirects after logout.

<script>
if(sec == 30){
</script>
    <?php
    $_SESSION["login_user"] = NULL;
    redirect_to("login.php");
    ?>
<script>
}
</script>

I hope this would work.

Upvotes: 1

Related Questions