Take time to access a page and write to DB

1

I need to take the time that the user was on a particular page, and the user to leave the page, this time be registered in the database.

Would anyone have any idea how to do it?

[Edited]

The time I was able to catch using javascript. The problem is to record this access time in the database. I tried to use the following code to send access time via POST and then capture and insert via mysql, but it did not work:

<form action="post" id="register_access">
    <input type="hidden" value="1" name="access_time" id="access_time"/>        
</form>
<script>
var contador = 0;

setTimeout(temporizador,1000);

function temporizador() {
  if(contador < 10000000){
    setTimeout(temporizador,1000);
  }
  document.getElementById('access_time').value = contador;
  contador++;
}

jQuery(document).ready(function($){

    $(window).on('beforeunload', function(e) {
      $('#register_access').submit();
      //return 'Are you sure?';
    });

});
</script>
    
asked by anonymous 16.07.2015 / 15:51

1 answer

1

First (and obviously) you need a table to store this information:

Tabela
 - ID
 - Session
 - Page
 - User
 - DateStart
 - DateEnd

Create a function to send data to server:

<script>
  function temporizador(time) {
    var dados = {
      page: window.location.pathname
    };

    var posttimeurl = 'http://endereco/para/cadastrar/tempo.php';

    $.ajax({
      url: posttimeurl,
      type: 'POST',
      dataType: json,
      data: dados,
      success: function(json){
        console.log(json);
      },
      error: function(x, s, h){
        console.log(s, x);
      }, 
      complete: function(){
        setTimeout(function(){ temporizador(time); }, time);
      }
    });

  };
  // Inicia o fluxo 
  temporizador(1000); // Tempo enviado no parâmetro
</script>

Receive the data on the server and register with the bank:

<?php

  session_start();

  $ret = Array('success' => FALSE, 'msg' => '');

  if (empty($_POST['page'])){
    $ret['msg'] = 'Página inválida';
    exit( json_encode($ret) );
  }

  // Se usuário logado coloque o ID dele, exemplo:
  // $userID = $_SESSION['user']['id'];

  $dados = Array(
    'session' => session_id(),
    'page' => $_POST['page'],
    'user' => '' // ou $userID
  );


  // Ou faça um UPDATE se a sessão já existir
  $sql  = "SELECT id FROM tabela WHERE 'session' = '{$dados['session']}' AND 'page' = '{$dados['page']}';";
  $id = $res['id'];
  // Insira $dados no banco se a sessão não existir
  $sql  = "INSERT INTO tabela ('session', 'page', 'user', 'datestart', 'dateend') 
           VALUES ('{$dados['session']}', '{$dados['page']}', '{$dados['user']}', NOW(), NOW());";

  // Se a sessão existir faça um UPDATE
  $sql  = "UPDATE tabela SET 'dateend' = NOW() WHERE id = {$id}";

  $ret['success'] = TRUE;
  $ret['msg']     = 'Dados registrados/atualizados';

  exit( json_encode($ret) );

So you'll have a log of how long each session lasted on each page. You can even store the IP, Browser, Resolution and etc ...

    
16.07.2015 / 16:39