Anurag Singh
Anurag Singh

Reputation: 727

how the session time out works in websites

here i am posting a sample code which gives me correct result. which means if i do not do any action for 60s than i am automatically log out from the page.let have the code below

<?php
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();

now the problem is that inside ISSET() function we are calculating $sessionTTL. now in that we have two operands first one is time() which gives the current time and the second one is $_SESSION["timeout] and this timeout also contains the current time, so the difference of both will be zero at all time.So how this code is able to make out that i am idle for 60 second and is able to destroy the session. Please explain the concept behind this!

Upvotes: 1

Views: 233

Answers (1)

aufziehvogel
aufziehvogel

Reputation: 7297

Consider you are calling the website for the first time. We assume the current timestamp is 100. Then the value of $_SESSION["timeout"] will have been set to 100.

Please note that the assignment of time() to $_SESSION["timeout"] is at the end of the script.

5 seconds later the user clicks on a link and after these five seconds visits another page. Then the script will be executed and $sessionTTL = time() - $_SESSION["timeout"]; will be calculated. Since we are five seconds further in time now, time() will return 105. However, $_SESSION["timeout"] will still contain 100, because it would be set again at the end of the script (which the script has not reached yet during execution). The difference will then be 5 seconds. Since 5 < 600, the branch will not be taken and $_SESSION["timeout"] can be set to the current time (105) once again.

Now the user waits for 20 minutes, which is 1200 seconds. He then clicks on a link.

Values now are:

$_SESSION["timeout"]: 105
time(): 1305

So the difference this time will be 1200 and thus larger than 600, so the condition block will be executed and the session will be destroyed.

Upvotes: 1

Related Questions