Is it possible to create a function in PHP to check if a session exists and accurately track user activity in real-time?
To check if a session exists and accurately track user activity in real-time, you can create a function in PHP that checks if a session is active and updates a timestamp in the session data to track user activity. This function can be called on each page load to ensure the session is active and update the timestamp accordingly.
<?php
// Function to check if a session exists and update user activity timestamp
function trackUserActivity() {
session_start();
// Check if session exists
if(isset($_SESSION['user_id'])) {
// Update user activity timestamp
$_SESSION['last_activity'] = time();
}
}
// Call the function on each page load
trackUserActivity();
?>