What role does session management play in determining the online status of registered users in a PHP script?

Session management plays a crucial role in determining the online status of registered users in a PHP script by tracking when a user last accessed the website. By updating a user's last activity timestamp in the session data on each page load, we can check if a user has been active within a certain time frame to determine their online status.

session_start();

// Update user's last activity timestamp in session data
$_SESSION['last_activity'] = time();

// Check if user has been active within the last 5 minutes
$inactive_time = 5 * 60; // 5 minutes in seconds
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $inactive_time)) {
    // User is offline
    echo "User is offline";
} else {
    // User is online
    echo "User is online";
}