User session time

2

Good community. When the user logs in I add in the database the day and time that this user logged in.

The file init.php , which contains the login and which I use on all my pages I put the following code:

if(($_SESSION['last_login'])>2){
//echo "ok";
}else{

header("location: logout.php?timeout=1");
}  

Now, I wanted the user after 30 minutes to be redirected to the logout page. Am I doing it right? Date format 2016-01-29 14:19:45

    
asked by anonymous 30.01.2016 / 17:47

2 answers

2

I do not see the need to write to banco de dados , use only session variables. Here's a simple example doing it in 30 seconds:

login.php

<?php

session_start();
if(!isset($_SESSION['start_login'])) { // se não tiver pego tempo que logou
    $_SESSION['start_login'] = time(); //pega tempo que logou
    // adiciona 30 segundos ao tempo e grava em outra variável de sessão
    $_SESSION['logout_time'] = $_SESSION['start_login'] + 30; 
}

// se o tempo atual for maior que o tempo de logout
if(time() >= $_SESSION['logout_time']) { 
    header("location:logout.php"); //vai para logout
    session_destroy();
} else {
    $red = $_SESSION['logout_time'] - time(); // tempo que falta
    echo "Início de sessão: ".$_SESSION['start_login']."<br>";
    echo "Redirecionando em ".$red." segundos.<br>";
}

?>

logout.php

<?php

echo "logout\n<br>";
session_start();
session_destroy();

?>
<a href="login.php">Voltar</a>

To put 30 minutos put 30 * 60 .

    
30.01.2016 / 18:06
0

PHP already has a session.gc_maxlifetime parameter, which can be changed.

Edit PHP.ini:

session.gc_maxlifetime = 1800

This will expire the session after 1800 seconds (30 minutes).

Verify that the session exists:

So just check if the session exists:

<?php

if(isset($_SESSION['sua_sessao'])){
// Se houver sessão - OK
}else{
header('location: logout.php');
// Se não houver - Redireciona para logout.php
}

?>

The session will expire in 30 minutes and will redirect to logout.php.

Problems and fixes:

Suppose a user NEVER logged in, if he accesses the page he will be redirected to logout.php, because he also does not have a session, which in my opinion would be wrong.

So create a cookie when you log in and check as follows:

<?php

//...
}else{

if(isset($_COOKIE['login'])){
// Se existe o cookie, que já indica que o usuário já se conectou alguma vez
    header('location: logout.php');
    // Redireciona para logout.
}else{
// Se o visitante caiu de paraquedas na página e nunca fez o login
    header('location: login.php');
    // Redireciona para o login.
}

?>
    
30.01.2016 / 22:11