How can JavaScript be used in conjunction with PHP to handle automatic logout functionalities?

When a user logs in to a website, a PHP session is typically created to keep track of their login status. To implement automatic logout functionality after a certain period of inactivity, JavaScript can be used to set a timer that triggers a PHP script to destroy the session when the timeout is reached.

<?php
session_start();

// Set the timeout period in seconds
$timeout = 1800; // 30 minutes

// Check if the user is logged in and if the last activity time is set
if (isset($_SESSION['loggedin']) && isset($_SESSION['last_activity'])) {
    // Calculate the time since the last activity
    $inactive_time = time() - $_SESSION['last_activity'];

    // If the user has been inactive for longer than the timeout period, destroy the session
    if ($inactive_time > $timeout) {
        session_unset();
        session_destroy();
        header("Location: logout.php");
        exit;
    }
}

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