[PHP] calculating the time spent on a page

FromHollandWithLove

Junior Member
Sep 14, 2002
11
0
0
Hi. I am working on a webstats scipt that should enter into a Mysql database how much time a user spends on a webpage.

Here is how my method goes:

Each page of my website contains a Javascript call to an image taht is actually a PHP script, like this:

statImg = new Image();
statImg.src = "counter.php?a='+browser+'&b='+sys+'&c='+referrer+'&d='+ip+'&e='+page+'";

Browser, sys, referrer, etc are Javascript variables sent on the query string to the php script.
The PHP script, counter.php, grabs these variables from the query string and puts them in a Mysql databse.

How can i get the time someone spends on a page using this method?

I was thinking of letting counter.php set $enter_time=time() to set the start time of the visit. Then i will need a variable $leave_time=time() when the user leaves the page (in whatever way). Then i can calculate the time spent on the page in seconds: $time_spent = $leave_time - $enter_time.

How do i set $leave_time?
I could do this by letting javascript create a popup when a user leaves the page. The popup will contain a php script that sets $leave_time, extracts $enter_time from the database, calculates $time_spent and writes it to the database. However this seems very unprofessional. Isn't there a better way?


 

notfred

Lifer
Feb 12, 2001
38,241
4
0
There is no reliabel way to do this. What if the person leaves the page opens and goes to get lunch? Or the user's machine crashes and leave_time is never returned?
 

FromHollandWithLove

Junior Member
Sep 14, 2002
11
0
0
I doesn't have to be reliable in such cases. If i see "8 hours 2 minutes and 5 seconds" i know someone has left the page open for a day.
Or i coud set a maximum time or something. But eeeeehm, anyone knows how to calculate this time?

I think the method described above will work, but it is so very inellegant.
 

kranky

Elite Member
Oct 9, 1999
21,019
156
106
You might find the information that starts here to be useful.

I would just store enter_time. Then, by looking through the MySQL data, you can calculate the time delta between page visits. The problem is that all the places on the net where pages are cached between you and the end user will throw you off. You'll never know the visit time for the last page because when they leave your site you can't see that.
 

FromHollandWithLove

Junior Member
Sep 14, 2002
11
0
0
Hey, that's a good idea! Hadn't thought of it myself.

There even is a way to catch the "browser close" event with javscript, by testing for Onunload (page unloaded) and !Onclik (no link klicked). When the page is unloaded and no link is clicked, this means the browser window is closed (or, unfortunately, reloaded). I can make a popup window on this event containing some PHP that writes $leave_time. Thanks!