How can online user activity be tracked and displayed in PHP using sessions?
To track online user activity in PHP using sessions, you can create a session variable to store the timestamp of the user's last activity. By updating this timestamp on each page load, you can track when the user was last active. You can then display this information to the user by retrieving the timestamp and calculating the time elapsed since their last activity.
<?php
session_start();
// Update user's last activity timestamp
$_SESSION['last_activity'] = time();
// Display user's last activity time
if(isset($_SESSION['last_activity'])){
$timeElapsed = time() - $_SESSION['last_activity'];
echo "Last active: " . $timeElapsed . " seconds ago";
}
?>
Keywords
Related Questions
- How can the error "Warning: Cannot modify header information - headers already sent" be avoided in PHP scripts?
- What is the potential risk of automatically submitting a form after a certain time delay in PHP?
- What are some best practices for dynamically triggering functions in PHP when clicking on multiple buttons?