Smith
Smith

Reputation: 5961

inteligently expiring sessions automatically

I am trying to code an automatic session timeout function in php, currently, this is what i have

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1200)) {
    // last request was more than 20 minutes ago
    // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

This technique depends on the user loading a page before he is notified of his expiration and i need to check on pageload.

I need one that expires weather the user loads a page or not. This is because other users loggedin to the site are notified when a session expires, and data is recorded in the database for further use.

Upvotes: 0

Views: 149

Answers (1)

cardeol
cardeol

Reputation: 2238

This is a quite complex topic, but you can manage implementing a session handler interface and a database handler.

  1. Check session.gc_maxlifetime and session.cookie_lifetime in PHP config

    This is a very good article about session settings: How do I expire a PHP session after 30 minutes?

  2. Create the database layer implementing SessionHandlerInterface and session_set_save_handler() with these methods.

    • SessionHandlerInterface::close — Close the session
    • SessionHandlerInterface::destroy — Destroy a session
    • SessionHandlerInterface::gc — Cleanup old sessions
    • SessionHandlerInterface::open — Initialize session
    • SessionHandlerInterface::read — Read session data
    • SessionHandlerInterface::write — Write session data

Tutorial: http://www.wikihow.com/Create-a-Secure-Session-Managment-System-in-PHP-and-MySQL

Finally you can query the database anytime to get offline and online users.

Upvotes: 1

Related Questions