Take time to access a page and write to the BD

Asked

Viewed 871 times

1

I need to take the time that the user was on a given page, and the user leave the page, this time is recorded in the database.

Would anyone have any idea how to do?

[Edited]

The time I managed to get using javascript. The problem is recording this access time in the database. I tried to use the following code to send the access time via POST and then capture and insert via mysql, but it didn’t 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>
  • This would be done with javascript

  • It’s a website, or a system?

  • In this case it would be a Kaduamaral site...

  • Why don’t you use the Google Analytics?

  • I need to record the access time in my database. Google Analytics does not roll pro that I want to do Kaduamaral... still worth.

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 the data to the 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 in the database:

<?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 will have a log of how long each session lasted on each page. You can still store the IP, Browser, Resolution and etc...

  • Obviously the table and the mysql commands I already have friend Kadu Amaral, I just did not post the whole code... my problem is that the code I posted was not able to send the data via POST. I will analyze the code you posted and try to implement here, then put the results.. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.