PHP $_SESSION 和 $_COOKIE 奇怪的行为

我正在尝试将 COOKIES 安装到我的网站中。

我在 GitHub 上找到了一个脚本:https ://github.com/jotaroita/secure-login-php7-remember-register-resetpw


我已经实现了脚本,并且能够登录。

我可以只使用 SESSION 登录,或者我可以同时使用 SESSION 登录并设置“记住我 -COOKIE”。


为了测试 COOKIE,我将 SESSION 设置为 1 分钟后过期。$expireAfter = 1;


Senario:

我登录网站并勾选“记住我”。会话开始并设置了 cookie。一切都很好!

## last action: 1 seconds ago

skip the cookie check: session already set


我等待 60 秒并重新加载页面。会话销毁并且 Cookie 读取:

## last action: 108 seconds ago

session destroy for inactivity

cookie read

cookie valid format

cookie right selector

cookie right token

set a new token in DB and in cookie

session set<-在此消息中我可以输出会话数据:$_SESSION['user']始终

但在我的其他页面(home.php)$_SESSION['user']中是空的?!(我包括来自:check.php 的 SESSION 和 COOKIE 检查)if(isset($_SESSION['last_action'])){返回 true


如果我再等 60 秒并重新加载页面,则if(isset($_SESSION['last_action'])){返回 false。但是现在$_SESSION['user']设置好了。


如果我再等 60 秒并重新加载页面。if(isset($_SESSION['last_action'])){返回真。但现在$_SESSION['user']是空的。


主页.php


<?php

//START SESSION

session_start();


//CONNECT TO DB, SET HEADER, SET TIMEZONE, CHECK FOR LOGIN-COOKIES

include("check.php");


//CHECK IF SESSION EXIST

if(!isset($_SESSION['user'])) {

    $isSesstion = false;

    header("Location: /index.php");

}

else{

    $isSesstion = true;

}

.....

那么,代码有什么问题?
为什么每次刷新网页时 $_SESSION 都会充满数据?为什么每次刷新页面
都不返回true?以及为什么 $_SESSION 一直在调试消息中携带数据......但它没有被携带到 home.php 中?if(isset($_SESSION['last_action'])){
session set ".$_SESSION['user']['usr_fname']."include(check.php");

你需要更多的代码吗?只是要求它!



ITMISS
浏览 73回答 1
1回答

慕尼黑8549860

我想我发现了问题。取消设置并销毁会话后。我不得不开始一个新的会话。奇怪的是,这种情况每秒钟才发生一次。但是添加session_start();解决了问题!if(isset($_SESSION['last_action'])){&nbsp; $secondsInactive = time() - $_SESSION['last_action'];&nbsp; $expireAfterSeconds = $expireAfter * 60;&nbsp; $debug.="last action: $secondsInactive seconds ago<br>";&nbsp; if($secondsInactive >= $expireAfterSeconds){&nbsp; &nbsp; //User has been inactive for too long.&nbsp; &nbsp; //Kill their session.&nbsp; &nbsp; session_unset();&nbsp; &nbsp; session_destroy();&nbsp; &nbsp; $debug.="session destroy for inactivity<br>";&nbsp; }&nbsp;&nbsp;}...session_start();$_SESSION['user'] = $session_data;...
打开App,查看更多内容
随时随地看视频慕课网APP