Calculate logged in time - PHP

Asked

Viewed 2,064 times

4

Does anyone know how I can calculate the total amount of time a user is logged in to my site? Whereas you need to pause the time count when closing the browser.

  • http://answall.com/questions/75071/pega-tempo-acesso%C3%A0-uma-p%C3%A1gina-e-gravar-no-bd

  • It is not possible to detect that the browser has closed efficiently, please read these links to understand http://answall.com/a/70316/3635 and http://answall.com/a/71023/3635

2 answers

3

My System for checking logged in user

I put in the include header this jquery

<script type="text/javascript">
    function insereLog()
        {
            $.ajax({
                url: "funcoes.php?acao=log"
            });
        }
         setInterval(function(){ insereLog(); }, 60000); // a cada minuto ele dispara essa funcão e manda um post naquele arquivo funcoes.php
 </script>

In the file functions.php

<?php
include("conexao_banco.php");//arquivo conexão ao banco
include("res_trito.php"); // arquivo que verifica se o usuário acesso a paginas session etc
if($_GET["acao"] == "log") //post recebido da  funcao inserelog do jquery
{
session_start();
mysql_query("UPDATE usuarios_sistema SET ultimo_acesso = DATE_ADD( NOW()) Where usuario = '$_SESSION[usuario que esta logado]' ");
}
?>

Ai you create a table in the bank with the examples fields I quoted so:

user.

And finally you create a file that checks online users from time to time

verfificar_usuarios.php

$inicio = substr($logout,11); // vc faz um select no banco antes disso e guarda a ultima hora acessada nessa variável $logout. Caso tenha mais de um usuário(claro que vai ter né :) ) vc faz um while e coloca isso tudo dentro do while pra ele verificar vários usuários.
$fim = new DateTime();
$inicio = DateTime::createFromFormat('H:i:s', $inicio);
$intervalo = $inicio->diff($fim);
$diferenca = $intervalo->format('%H:%I:%S');

 if ($diferenca > '00:10:00') {//vc define o intervalo para remover o usuario online
     //Se tiver mais de 10 minutos sem acesso vc faz uma ação como update tirando status de 1 para 0 na sua tabela de usuários 
 } 

This file I put in a cron task to run from time to time ai vc set its priority. If you like the answer ai :)

1


Saves the date the user entered the system into a table and the time it exits. In mysql use NOW() to bring the current time, if the time zone has different use DATE_ADD( NOW( ) , INTERVAL +3 HOUR ). And adjust the hours according to your server.

Regarding the issue of closing the browser I use other features as every 5min check if it is online if I do not log the output.

  • I use two methods: 1. Each page that he accesses updates the time in the table, I run a cron task every 10min and compare the last access with the current time if it is greater than 10min I remove it. 2. I do the same scheme only that in Sesssion every page update Sesssion adds 10min if it goes past that and it will update destroy Sesssion and direct to login. if you want the function to compare time I have :)

  • How do you advise checking if you are online? Javascript, crontab, or with what? From what I saw, javascript seems easier, but maybe not the most advised, mainly because it can be blocked in the browser.

  • in my system I put a status in the bank table when the user enters the system, type 0 offline and 1 online then only change when he login or logout. and as I said earlier I run a function for x time to see if he updated for a period the page or passed to another.

Browser other questions tagged

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