tags:

views:

151

answers:

3

I am looking for a way to check on the life of a php session, and return the number of seconds a session has been "alive".

Is there a php function that I am missing out on?

+2  A: 

You could simply store the timestamp on which the session was created in the session

Martin
+6  A: 

You could store the time when the session has been initialized and return that value:

session_start();
if (!isset($_SESSION['CREATED'])) {
    $_SESSION['CREATED'] = time();
}

And for retrieving that information from an arbitrary session:

function getSessionLifetime($sid)
{
    $oldSid = session_id();
    if ($oldSid) {
        session_write_close();
    }
    session_id($sid);
    session_start();
    if (!isset($_SESSION['CREATED'])) {
        return false;
    }
    $created = $_SESSION['CREATED'];
    session_write_close();
    if ($oldSid) {
        session_id($oldSid);
        session_start();
    }
    return time() - $created;
}
Gumbo
Your code smells to me, because you don't return the session lifetime! You just return the time at which it was created, yet the name of the method is getSessionLifetime(). Your method should be named getSessionStartTime() instead, or change the method to calculate the actual elapsed time.
RibaldEddie
You’re right, thanks.
Gumbo
Also, don't bother returning false. IF you are going to calculate the session lifetime, then return zero, since the session has been alive for zero time units. IF you are going to get the session start timea and the session is new, then you will want to return time().
RibaldEddie
+2  A: 

I think there are two options neither are great but here they are.

1) If you have access to the file system you can check the creation timestamp on the session file.

2) Store the creation time in the session e.g.

session_start();
if( ! isset($_SESSION['generated'])) {
    $_SESSION['generated'] = time();
}
zodeus
Your example would override the value on every request.
Gumbo
You're right, I was only demonstrating the idea not the implementation.
zodeus