How to check if the user logged in 1 hour ago or is logged in

1

I'm creating a system to verify that the user entered the site 1 hour ago or earlier. There is a column in the database that says the last time you logged in. Last_Login (int4) the date has to be in ymdHm format (1703221703).

My problem is that I do not know how I can check this, whether he logged in 1 hour ago or before, or if he is logged in.

My code I've done so far:

    public function check_time(){
    $date = new \DateTime();
    //echo $date->format('ymdHm');
    $conexao = new Config;
    try{
        $conect = $conexao->getConn();
        $prepare = $conect->prepare("SELECT * FROM accounts WHERE login = ?");
        $prepare->bindvalue(1, $_SESSION['username']);
        $prepare->execute();
        $dados = $prepare->fetch(PDO::FETCH_ASSOC);
        if ($prepare->rowCount() >= 1){
            //return $dados['last_login'];
            if($dados['last_login'] == 

        }



    }catch(PDOException $e){
        echo "Erro: ".$e->getMessage();
    }
}
    
asked by anonymous 22.03.2017 / 18:21

1 answer

1

I'll assume you know how to do the query in the bank and get the feedback.

Considering that you saved the bank's return in the variable $retorno :

$zonaTemporal = new \DateTimeZone('America/Sao_Paulo');

$retorno = '201703221525';

$logouEm = \DateTime::createFromFormat('YmdHi', $retorno, $zonaTemporal);

if($logouEm == null) {
  /* Data Inválida no Banco, faz algum tratamento */
}

$intervalo = new \DateInterval('PT1H');

$agora = new \DateTime('now', $zonaTemporal);

$logouEm = $logouEm->add($intervalo);

echo 'Fez o último login em:<br>' . $logouEm->format('Y-m-d H:i:s');
echo '<br>';

echo 'Agora é:<br>' . $agora->format('Y-m-d H:i:s');
echo '<br><br>';


if($logouEm > $agora) {
    echo 'Logou a mais de uma hora';
} else {
    echo 'Ainda não deu uma hora';
}

Note : In this example I'm assuming the hours are saved with the Brazilian time zone. This may not be your case. I recommend that you change the time zone to be in accordance with the mode you are saving. If you do not know which time zone is saved in the database, it is probably the default value of your php.ini, which is usually the same as the time zone of the computer running php.

    
22.03.2017 / 20:45