22

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?

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Walker
  • 128,495
  • 27
  • 68
  • 94
  • 2
    Can't you use the Google Analytics data? – ChrisF Aug 20 '10 at 21:14
  • 2
    There are already a dozen packages that do this. Don't reinvent the wheel if you don't have to. Look into webalizer, awstats, urchin, etc. This is actually a non-trivial problem. Defining "time on site" requires making some assumptions, since you only know when a browser requests content, not when a user closes a window, navigates to a remote site, etc. – Frank Farmer Aug 20 '10 at 21:18
  • 1
    We're offering a job board that allows administrators to come in and take control of specific segments of the userbase, and we want to provide administrative analytics for them. – Walker Aug 20 '10 at 21:24

5 Answers5

27

You can get the time in next ways:

  1. Once user visit your site, save current time at cookie as "visited", and at next visit you can grab it, if it was set.
  2. And more expensive method: when the page loads, start js timer, and on page unload send to server time which user sent and save it to db.
  3. And if window.unload does not work at Opera, you can send time to server every 5 seconds, and stores it to DB.

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

Vladimir Vukanac
  • 944
  • 16
  • 29
Dmytro Krasun
  • 1,714
  • 1
  • 13
  • 20
  • Awesome, thanks for the help - I'd love to see a script if you have the time to write a quick one? Can I use page.unload over an entire domain? – Walker Aug 20 '10 at 21:27
  • Wait, i start to write script – Dmytro Krasun Aug 20 '10 at 21:29
  • many times the ajax call not working .. before sending ajax request page unload is happening . so couldn't store leave time many times – Gowri Feb 12 '11 at 10:47
  • @DmytroKrasun Not just Opera, it won't work in Safari IOS as well, the most common browser for IOS devices including Ipad. It is very tricky to capture this metric in real-time because at the moment you are capturing the stay time and sending to DB, page is also closed simultaneously. Also, you need to subtract idle time, window minimize, tab focus change etc. So, we wrote a modern tracker for Web 2.0 that captures this data in real-time using **sendBeacon()** API for most browsers and using **LocalStorage** techniques to send the data for Safari IOS to prevent data loss, an answer below. – webblover Oct 27 '22 at 09:47
4

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:

  1. Access the page, generate a code (let's say page: index.php code: 2345)
  2. Store this in a database table with their IP, and visit time
  3. Unload event fire, call the AJAX, passing the page & code
  4. Look up in the DB for the IP, page, and code, and log the leave time

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.

Tarka
  • 4,041
  • 2
  • 22
  • 33
  • 1
    And what will you do, if at Opera browser unload event doesn`t works? – Dmytro Krasun Aug 20 '10 at 21:24
  • 1
    @DimaKrasun I dind't realize that would be an issue. Thought it was supported in all browsers, but I haven't touched Opera much at all. Learn something new every day. – Tarka Aug 23 '10 at 02:04
3

Use timeonsite JS for web and mobile browsers. It tracks time on site accurately.

<script type="text/javascript">
        var Tos;
        (function(d, s, id, file) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s);
            js.id = id;
            js.onload = function() {
                var config = {
                    trackBy: 'seconds' 
                };
                if (TimeOnSiteTracker) {
                    Tos = new TimeOnSiteTracker(config);
                }
            };
            js.src = file;fjs.parentNode.insertBefore(js, fjs);
        } (document, 'script', 'TimeOnSiteTracker', 'https://cdnjs.cloudflare.com/ajax/libs/timeonsite/1.2.0/timeonsitetracker.min.js'));
    </script> 

At the page end, call

<script>
    Tos.getTimeOnPage();
        //Response ->
        {
            TOSId: 1129620185532,
            TOSSessionKey: "14802525481391382263",
            TOSUserId: "anonymous",
            title: "Test application - TimeOnSiteTracker",
            URL: "http://tos-localdata.chennai/home.php"
            entryTime: "2016-11-27 13:15:48.663",
            currentTime: "2016-11-27 13:17:31.663",
            timeOnPage: 103,
            timeOnSite: 0,
            timeOnPageTrackedBy: "second",
            timeOnPageByDuration: "0d 00h 01m 43s",
            timeOnSiteByDuration: "0d 00h 00m 00s",
            trackingType: "tos",
        }
</script>

As simple as that,

It seems to work even in mobile browsers like IPhone, IPad, mobile Safari etc. that doesn't support window.unload() events natively.

webblover
  • 1,196
  • 2
  • 12
  • 30
1

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.

bimbom22
  • 4,510
  • 2
  • 31
  • 46
-1

$(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}
              });