我刚刚为我的网站实施了最后一次看到的系统。您的第一个选项类似,但我仅每 +-5 分钟更新一次。它适用于我的情况,但大型网站可能需要一些额外的东西。
<?php
function updateLastSeen($user_ref, $session_id, $db) { /*Parameters: The user's primary key, the user's session id, the connection to the database*/
$timestamp = date('Y-m-d H:i:s');
if ($session_id !== '') {
/*logged in*/
$sql_check = "SELECT user_id FROM user_last_seen WHERE user_id = ?";
$stmt_check = $db->prepare($sql_check);
$stmt_check->bind_param('s', $user_ref);
$result_check = $stmt_check->execute();
$stmt_result_check = $stmt_check->get_result();
if ($stmt_result_check->num_rows > 0) { /*If the user's last seen was previously recorded, update his record*/
$sql = "UPDATE user_last_seen SET last_seen = ? WHERE user_id = ?";
} else { /*Otherwise, insert a record for him*/
$sql = "INSERT INTO user_last_seen (last_seen, user_id) VALUES (?,?)";
}
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $timestamp, $user_ref);
$result = $stmt->execute();
}
}
if( !isset($_SESSION['lastSeen']) ){ /*User logs into the website or lands on the current page, create a lastSeen variable*/
$_SESSION['lastSeen'] = time();
updateLastSeen($user_ref, $session_id, $db);
} else {
$last_seen_time_difference = (time() - $_SESSION['lastSeen']) / 60;
if ($last_seen_time_difference > 5) { //if the difference between now and the lastSeen is 5 minutes or more, record his last seen.
updateLastSeen($user_ref, $session_id, $db);
$_SESSION['lastSeen'] = time(); /*after updating the database, reset the lastSeen time to now.*/
}/* else {
//do nothing. Don't update database if lastSeen is less than 5 minutes ago. This prevents unnecessary database hits.
}*/
}