How can PHP sessions be effectively managed to handle user activity and logouts?

To effectively manage PHP sessions for user activity and logouts, you can set session variables to track user activity and implement a logout functionality that destroys the session data. By setting a timeout for the session, you can automatically log the user out after a period of inactivity.

// Start the session
session_start();

// Set session variable to track user activity
$_SESSION['last_activity'] = time();

// Check if user is logged out due to inactivity
$inactive = 600; // 10 minutes
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive)) {
    session_unset();
    session_destroy();
}

// Implement logout functionality
if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}