Reputation: 177
i want to track time spent on my site by an authenticated user.
To do that i have put this code on my layout:
function js_yyyy_mm_dd_hh_mm_ss (param) {
now = new Date(param);
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
var start;
$(document).ready(function() {
var d = new Date();
start = d.getTime();
});
<% if current_user %>
$(window).on('beforeunload', function() {
var d = new Date();
end = d.getTime();
timeSpent = (end-start)/1000;
page = window.location.toString();
debut=js_yyyy_mm_dd_hh_mm_ss(start);
fin=js_yyyy_mm_dd_hh_mm_ss(end);
$.ajax('<%= users_time_path %>', {
async: false,
type: 'POST',
data: {log_time:{start:debut, end: fin, timespent: timeSpent, page:page}},
success: function(res,status) { },
error: function (res, status) {
console.log('Server error: '+ status);
}
});
<% end %>
});
But with this code if the user have two tab open i count twice the time.
Futhermore if the user leave this computer with the tab open and come back two day later, i will count more than 48h...
What should I do to avoid that ?
How can i do thaht on server side to avoid fake time by users ?
thanks
Upvotes: 2
Views: 354
Reputation: 1196
You can use timeonsite tracker for this that captures authenticated users natively along with following other benefits:
Easy to use since pure JS code. It's also found in CDNjs & JSDeliver for quick integration
Upvotes: 1
Reputation: 91
Call the Server every 1-5 minutes (ajax or something), in php you have a session and the ip from the client, you can use booth to track and identify the user.
some links:
for your fake protection:
stop calling the server after 1 min without mousemove or something ...
Upvotes: 0