简体   繁体   中英

How do I keep a session alive in new tab PHP

I'm struggling with sessions in php. Usually, everything is ok but sometimes, if I open the web in a new tab (via link or directly via typing), the session dies, even though the session is still alive in the first tab. It's quite annoying, I would appreciate any help.

Here is my simplyfied code for logging in

<?php
session_set_cookie_params(1800,"/");
session_start();

if(isset($_POST['go']))
{
// do the checking
if login and password is correct
{
// do some stuff

//ini_set('session.cookie_lifetime', 1800);
//ini_set('session.gc_maxlifetime', 1800);
// I've tried both but there is no difference so I don't use it
}
}

?>

In the beggining of every page

<?php
session_set_cookie_params(1800,"/");
session_start();

I've searched for help and tried to use session_set_cookie_params(1800,"/") before session_start but I see no difference.

edit: I'm sorry, I wasn't specific. After a succesfull check, I put the user ID from db and timestamp of last activity in the variables:

$_SESSION['id'] = $result['id'];
$_SESSION["LAST_ACTIVITY"] = time();

and then, at the beginning I check if the id variable is not empty and if not, update last activity timestamp:

if(isset($_SESSION['id']))
{

if ((time() - $_SESSION["LAST_ACTIVITY"] > 1800)) 
{
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
}
else 
{   
$time = time();
$_SESSION["LAST_ACTIVITY"] = $time; // update last activity time stamp
} 

}

You should put something like the UserID in a $_SESSION variable, right after the user login.

$_SESSION['userID'] = $_POST['userID'];

As RepeaterCreeper said, the session will remain alive until your cookies / cache are cleared (or until they expires)

The only thing left to do is to add a check at the beginning of each page to see if the user is logged. You can use the $_SESSION variable containing the userID to verify that the user is logged. If he isn't, just redirect him to your login page. :

if (!isset($_SESSION['userID'])) { 
    header ('location: loginpage.php'); 
} 

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