简体   繁体   English

如何在新标签的PHP中保持会话有效

[英]How do I keep a session alive in new tab PHP

I'm struggling with sessions in php. 我正在用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. 我一直在寻求帮助,并尝试在session_start之前使用session_set_cookie_params(1800,“ /”),但没有发现任何区别。

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: 成功检查之后,我将db中的用户ID和上次活动的时间戳记放入变量中:

$_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: 然后,首先,我检查id变量是否不为空,如果不是,则更新上一个活动时间戳记:

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的名称。

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

As RepeaterCreeper said, the session will remain alive until your cookies / cache are cleared (or until they expires) 正如RepeaterCreeper所说的,会话将保持活动状态,直到您的cookie /缓存被清除(或直到它们过期)为止。

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. 您可以使用包含userID的$ _SESSION变量来验证是否已登录用户。 If he isn't, just redirect him to your login page. 如果不是,只需将他重定向到您的登录页面。 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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