What are some best practices for tracking user activity and online status in a PHP-based website?
Tracking user activity and online status in a PHP-based website can be achieved by using sessions or database entries to store user activity timestamps. By updating these timestamps regularly, you can track when a user was last active and determine their online status. Additionally, you can use AJAX requests to periodically update the user's activity status without requiring a page reload.
// Update user activity timestamp in session
session_start();
$_SESSION['last_activity'] = time();
// Check if user is online based on last activity timestamp
function isUserOnline($timeout = 300) {
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] <= $timeout)) {
return true;
}
return false;
}
// Example usage
if(isUserOnline()) {
echo "User is online";
} else {
echo "User is offline";
}
Related Questions
- What are the advantages of using a Query Builder in PHP for dynamic SQL queries, especially in the context of dependent dropdowns?
- What is the purpose of using $_SESSION in PHP and how does it help in storing values across page refresh?
- What is the best way to process CSV data from a form using PHP?