Monday, April 25, 2011

PHP: return life of current session

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?

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

  • 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;
    }
    
    RibaldEddie : 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.
    Gumbo : You’re right, thanks.
    RibaldEddie : 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().
  • 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();
    }
    
    Gumbo : Your example would override the value on every request.
    zodeus : You're right, I was only demonstrating the idea not the implementation.

0 comments:

Post a Comment