Answer the question
In order to leave comments, you need to log in
How to correctly calculate the user's online time?
Tell me how, in your opinion, to correctly calculate the total time that the user was online?
For online, you can take a certain action that the user performs every 30 seconds.
It doesn't matter in what programming language - logic is interesting.
Answer the question
In order to leave comments, you need to log in
I think it would be more correct to store the beginning of authorization on the server side and record the "end" with each user action. On exit, consider the session ended. If there are no actions for more than n seconds, consider the last activity as "end".
It is wrong to consider any automatic requests as user activity IMHO.
However, everything very much depends on the specific case - both timeouts and storage method (still, current online and / or general). And even accounting for automatic requests.
Something like this comes to mind.
$mc = new Memcache;
$mc->connect('127.0.0.1', 11211);
$period = 30; // longpoll reconnect
$delay = 1; // reconnect delay
$uid = 1;
if(!$last_active = $mc->get("last_active_{$uid}")){
$mc->set("last_active_{$uid}", time());
die();
}
$now = time();
$online_time = $now - $last_active;
$counter = $mc->get("online_counter_{$uid}") ?: 0;
if($online_time < $period+$delay){
$counter += $online_time;
} else {
$counter += $period;
}
$mc->set("online_counter_{$uid}", $counter);
$mc->set("last_active_{$uid}", time());
echo "User ({$uid}) online time: {$counter}";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question