Does anyone know how I can calculate the total amount of time a user is logged into my site? Considering that you need to pause the time count when closing the browser.
Does anyone know how I can calculate the total amount of time a user is logged into my site? Considering that you need to pause the time count when closing the browser.
Saves the date that 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 is different use DATE_ADD( NOW( ) , INTERVAL +3 HOUR )
. And go adjust the hours according to your server.
As for the issue of closing the browser I use other features like every 5min check if it is online if I do not record the output.
My System to check logged-in user
I do not include this jquery header
<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 funcoes.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]' ");
}
?>
Now you create a table in the database with the example fields that I quoted like this:
user_system, status_online (0 or 1 where 0 and off and 1 online) or what you choose and a field last_access to update the time every 60 seconds and will update with the name of the user that is in the session. p>
And lastly you create a file that checks users online 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
}
I put this file in a cron job to run from time to time and set the priority. If you like the answer to this: