How can session expiration be managed in PHP to log out users after a period of inactivity?

Session expiration can be managed in PHP by setting a timeout period for the session. This can be achieved by using the session.gc_maxlifetime configuration directive in the php.ini file or by setting the session cookie expiration time. Additionally, you can implement a custom solution by tracking the user's last activity timestamp and checking it against the current time to log them out after a period of inactivity.

// Set session timeout period to 30 minutes
ini_set('session.gc_maxlifetime', 1800);

// Start the session
session_start();

// Check if last activity timestamp is set
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    // Log the user out and destroy the session
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}

// Update last activity timestamp
$_SESSION['last_activity'] = time();