How can PHP be used to check if a user has been active within the last 30 minutes without constantly updating a timestamp in a database?

To check if a user has been active within the last 30 minutes without constantly updating a timestamp in a database, you can use sessions in PHP to track user activity. By updating a session variable with the current timestamp each time the user interacts with the site, you can compare this timestamp to the current time to determine if the user has been active within the last 30 minutes.

session_start();

if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] < 1800)) {
    // User has been active within the last 30 minutes
    echo "User has been active within the last 30 minutes.";
} else {
    // User has not been active within the last 30 minutes
    echo "User has not been active within the last 30 minutes.";
}

$_SESSION['last_activity'] = time();