Search code examples
phpjavascriptjquerymatomo

How to track Visit Duration for 1 page website


I have a website page where most of the visitor will spend their time on. The site uses PHP with Codeigniter and jQuery.

Problem: However, I believe tracking systems like Piwik calculate the time spent on a page by subtracting the time the visitor leaves that page to a new page from the time he loads the page.

Is there a way around this? Maybe use javascript to trigger the tracking system so it knows that the visitor is leaving the page?


Solution

  • Edit: I added some "salting" to the $id, I don't know.. I get the feeling that it's even more unique, even though I think it's a bit unlikely that there will be similar IDs due to the use of micro seconds but just to be extra sure

    Something like this
    JQuery: Ajax request to StayAlive.php every 10 seconds

    function pingPing(){
        $.ajax(
        {
            type:'GET',
            url:'StayAlive.php', 
            success: function() 
            {
                setTimeout(pingPing, 10000);
            }
        }
    }
    


    PHP: StayAlive.php

    <?php
    function newUser(){
      $id=sha1($_SERVER['HTTP_USER_AGENT'].microtime().$_SERVER['REMOTE_ADDR']);
      setcookie("id", $id, time()+3600*24*365);
      //create new row in the database for that $id
    
    }
    if (isset($_COOKIE["id"])){
      //check if the id is in the database
      //if yes => time_spent+=10
      //if no => newUser();
    }
    else
      newUser();
    ?>