简体   繁体   中英

stop session from logging user out

I have some code that I added to try and prevent the user from auto logging out (session). - but it still logs the user after so long

What I want is for the user to be able to access multiple pages when logged in and not log them out if they go idle, hence why I put a large idle time - or in other words , stay logged in until they decide to click logout.

login-page

$result = mysqli_query($connection,$query) or die(mysql_error());
    $rows = mysqli_num_rows($result);
        if($rows==1){
        $_SESSION['username'] = $username;
        $_SESSION['username']=time();
            // Redirect user to index.php
        header("Location: admin-index.php");
         }else{
            $_SESSION['incorrect'] = 'Incorrect email or password. Please try again.';
            header ("Location: admin-login.php?=incorrectlogin");
    }
}

logged in index page

<?php 
session_start();
$idletime=6000000;
if (time()-$_SESSION['username']>$idletime){
    session_destroy();
    session_unset();
    header ("Location: admin-login.php");
}else{
    $_SESSION['username']=time();
}
//on session creation
$_SESSION['username']=time();
?>


<!DOCTYPE html>
<html lang="en" >

<head>

second php page

<?php
session_start();
        if(!isset($_SESSION["username"])){
header("Location: admin-login.php");
exit(); }
?>

There are a few ways of handling this:

You could change the lifespan of the sessions on the servers itself or if you can't access the server settings, you could try overwriting it through code:

ini_set('session.gc_maxlifetime', 6000000);

session.gc_maxlifetime manual

If you are unable to change the lifespan of sessions on the server, you could use this small code 'trick', keep in minde that if the clients pc shuts down or goes into sleep mode, the sessions will also expire:

Basicly you create a php script containing:

session_start();

Second you just write some jquery with the following code:

$(document).ready(function() {
    // keep alive
    setTimeout(keepalive(),120000);

});

function keepalive() {
    $.get( "url/to/ajax.php", function( data ) { setTimeout(callserver,12000);  });
}

You can use a trick, http://php.net/manual/en/function.session-start.php#example-5997

Starting with Php version 7.0 was added an option to prevent session expire. A time of 86400 means 1 days. You can adjust as you want.

if (session_status() == PHP_SESSION_NONE) {
  if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
    session_start(['cookie_lifetime' => 86400,]);
  } else {
    session_start();
  }
}

You can put at the top of Php files or include a file with this code on your project.

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM