Skip to content
PHP Logo

Are there any specific PHP functions or methods that can be used to implement automatic session logout features effectively?

To implement automatic session logout features effectively in PHP, you can use the `session.gc_maxlifetime` directive to set the maximum lifetime of a session. By setting this directive to a specific time, you can automatically log out users after a certain period of inactivity.

php
// Set the maximum session lifetime to 30 minutes
ini_set('session.gc_maxlifetime', 1800);

// Start the session
session_start();

// Check if the session is active
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // Unset all session variables
    $_SESSION = array();

    // Destroy the session
    session_destroy();
}

// Update the last activity time stamp
$_SESSION['LAST_ACTIVITY'] = time();