DevStarlight
DevStarlight

Reputation: 804

How to know how much time a user has our webpage open

I'm trying to guess how much time a user expend on my website in php. To do that, i was thinking that for every new action on my web, i could get the difference between the $_SERVER['REQUEST_TIME'] and the current. I would also be planning to get stats of my current hosting but i don't know if i can get these values via PHP request. I would like to get your point of view about using this first and second method, but in advice I should say i'm not really happy with the first option, cause server could be collapsed if the amount of petitions are really high..., otherwise I don't know any other way so if you could help me, it would be wonderful. On my website i'm using HTML5, CSS3, PHP, JavaScript, JQuery, AJAX and MySQL database. It is supposed i'd like to store and count all the time users stay logged in my webpage. Thanks in advice.

Upvotes: 0

Views: 504

Answers (1)

David
David

Reputation: 4361

There are a few ways of doing this, but only one way to get fairly accurate readings.

PHP Time Difference

This method is what you were talking about with checking the time difference. You would mark the time the user visited the page. Then when the visitor navigates to another page, you subtract the two times and you have the duration the user was looking at the previous page.

To hopefully make myself a little more clear, below is a basic layout of the actions you need to perform to make the PHP time difference method work.

  1. Log the current page URL and time(). Store this as a cookie / session / entry in the database.
  2. When the user visits a page, check the HTTP_REFERER variable and if it matches the page they were previously on, you can calculate the time they were on the last page. The referral check is needed to make sure they are not just opening a new tab and visiting your site again. You will also want to add a time limit so if the value is over 30 minutes it doesn't mark them as visiting the page for over 30 minutes.
  3. Keep repeating those actions and you will have a somewhat okay tracking method. This won't be that specific and in some cases not work if they don't send the referral header.

Javascript Tracking

You can send a "heatbeat" or a "ping" every few minutes to tell your server that the user is still on a specific page. You would want to send the URL the user is currently on as a parameter, don't rely on the HTTP Referral header to be sent. Using this method you can get very accurate readings. You could even track if the user is focused on the web browser window or not to check if the page is being read or just in the background.

Upvotes: 1

Related Questions