How can the header function be utilized in PHP to redirect users after a certain time limit for automatic logout?

To automatically log out users after a certain time limit, we can utilize the header function in PHP to redirect them to the logout page. By setting a timer and using the header function to redirect the user after the specified time, we can ensure that users are logged out automatically if they are inactive for too long.

// Set the time limit for automatic logout (e.g. 30 minutes)
$logout_time = 1800; // 30 minutes in seconds

// Start the session
session_start();

// Check if user is logged in and set the last activity time
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > $logout_time){
    // Redirect user to logout page
    header("Location: logout.php");
    exit;
}

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