Reputation: 57926
I use the following code to see how long a user is on a particular page. I use a hidden image with a src attribute to this script:
$timer_seconds = 1;
while(!connection_aborted()) {
echo "\n";
flush();
sleep(1);
$timer_seconds++;
}
I sometimes find this can be off by 5-10 seconds! I am guessing its the load of the server that effects the timing??
Is there anyway I can make this accurate?
Thanks all for any help.
Upvotes: 2
Views: 649
Reputation: 31
as @erjiang said echo and flush take time and after that you put script to sleep... so if for flush was needed 1 seccond and then you sleep 1 seccond thats 2 secconds and you add only one!
solution would be to write a start and end time and then find difference:
$start = time();
while(!connection_aborted()){
echo "\n"; //probably not needed...
flush(); //same probably not needed :)
sleep(1); //so just a sleep to not continue the code
}
$end = time();
$diff = $end - $start;
$days=floor($diff/86400);
$hours=floor(($diff-($days*86400))/3600);
$minutes=floor(($diff-(($days*86400)+($hours*3600)))/60);
$secconds=floor(($diff-((($days*86400)+($hours*3600))+($minutes*60))));
echo "\n\n".$hours."/".$minutes."/".$secconds;
that will do it! ;)
Upvotes: 0
Reputation: 5158
You've got some nice tools (in javascript) to do that.
these are some of used on the company i work.
Upvotes: 1
Reputation: 179086
Using jQuery you could make a synchronous ajax call onbeforeunload
(I know it's not exactly ajax any more) to tell how long the user was on the page.
The truth of the matter is that It really doesn't tell you much of anything. Just because someone is on a page doesn't mean they're looking at the page. Just because they look at the page very briefly, doesn't mean they dislike it either.
Upvotes: 2
Reputation: 45667
echo
and flush
can take time, so your loop sleeps for 1 second + the time spent on echo
and flush
. Try something like:
$begin_time = time();
$elapsed_time = 0;
while(!connection_aborted()) {
echo "\n";
flush();
sleep(1);
$elapsed_time = time() - $begin_time;
}
Upvotes: 4
Reputation:
You should probably use Javascript do this. E.g., request something from the client (using Ajax or an image request) on the unload event of the document.
Upvotes: 5
Reputation: 272517
There is no reliable way to do this from the server.
Upvotes: 0