I'm looking to track users average time on a website (in the same way that Google analytics does) for internal administration.
What's the easiest way to do this?
I'm looking to track users average time on a website (in the same way that Google analytics does) for internal administration.
What's the easiest way to do this?
You can get the time in next ways:
If you need, I can write an example script.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>Collect time</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var start = null;
$(window).load(function(event) {
start = event.timeStamp;
});
$(window).unload(function(event) {
var time = event.timeStamp - start;
$.post('/collect-user-time/ajax-backend.php', {time: time});
})
});
</script>
</head>
<body>
</body>
</html>
And backend script:
<?php
$time = intval($_POST['time']);
if (!file_exists('data.txt')) {
file_put_contents('data.txt', $time . "\n");
} else {
file_put_contents('data.txt', $time . "\n", FILE_APPEND);
}
But as I said it wouldn`t work at Opera browser
Main way I can think of:
When the user first hits a page, you log, say, their IP address, the page loaded, and the time. Then, using some Javascript and AJAX, when they leave the page, you use the unload
event to send to an AJAX handler that records the page and when they leave.
You would need to use some sort of ID, apart from a session, to store the page visit. Say I have 5 instances of the homepage open, you'd want to log each one individually. So, something like this:
index.php
code: 2345
)If they visit index.php
again, you would generate another code, say, 36789
. Use something that generates a random GUID is best, so you can (essentially) ignore any possibilities of collisions on the same IP/page/code combination.
There really isn't an effective way to do this with PHP, as PHP is server-side and provides no way of determining when the page was closed. You need to use javascript to determine this.
What I would do is use javascript to start a timer on window.onload
and then end the timer on window.onunload
. Then you can store the data and do what you want with it.
$(window).unload is a very good function to tracking user leaving page.
but one point is when window unload to send ajax sometime it now work, the ajax not finished when user leave page. so you need add one attribute (async: false) to ajax, code is blow:
$.ajax({
type: 'POST',
async: false,
url: '/collect-user-time/ajax-backend.php',
data: {time: time}
});