【问题标题】:$_SESSION is read after page reload only仅在页面重新加载后读取 $_SESSION
【发布时间】:2017-05-29 10:41:34
【问题描述】:

我最近正在尝试解决有关 Sessions 的一些问题,现在我需要帮助才能使用 XAMPP 让一个小页面正常工作。

我使用 4 页进行测试:
1)index.php是用户放置自己的ID和PW的页面。
2) logon.php 检查数据库中的匹配条目并将 einter 重定向到 index.phpprofile.php
3) profil.php 回显所有相关的用户数据
4) logout.php

测试 1:现在作为用户,我执行以下操作:我从 index.php 开始并输入我的 ID 和密码。假设我的 ID 是 1234。登录表明我很好,并将我重定向到 profil.php,显示用户 1234 的数据。现在我可以注销,会话被删除,一切看起来都很好。

测试 2:作为新用户,我从 index.php 开始,但现在我的 ID 是 5678。logon.php 告诉我一切都很好,并将我重定向到 profil.php,但它显示了第一次登录的数据( 1234)。我也可以移动到其他页面并返回profil.php,但数据将始终用于用户 1234,直到我刷新页面(F5 或 CTRL + SHIFT + R)。无论哪种方式,现在它都说明了正确的 5678 数据。我可以注销,会话将再次被销毁。

这是我处理会话的方式:

index.php:

<?php
    @session_start();
?>

logon.php

<?php
    @session_start();
    session_regenerate_id(true);
?>

profile.php:

<?php
    @session_start();
    if(!isset($_SESSION['personal_id'])){
        header('Location: /index.php');
        exit;
    }
?>

logout.php:

<?php
    @session_start();
    $_SESSION = array();
    setcookie( session_name(), "", time()-3600, session_save_path() );
    session_destroy();
    session_write_close();
?>

所有标题如下所示:

<head>
    <title>Scheffel Shoptime</title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />
    <meta http-equiv="Refresh" content="5;url=./index.php">
</head>

您是否已经知道我哪里出错了,或者您需要更多信息吗? 提前感谢所有试图提供帮助的人!

【问题讨论】:

  • 你为什么使用session_regenerate_id(true);?没有多大意义,如果不执行,这看起来可能是问题所在。
  • 你为什么要这么做@session_start();
  • 我还在学习如何使用会话。我浏览了 * 上的其他页面,说明我应该使用 session_start();在每一页上。
  • 我评论了 session_regenerate_id(true);出,但这似乎不是问题。我用它来确保每次登录时都使用新会话。
  • 你在哪里实际设置$_SESSION['personal_id']

标签: php mysql session


【解决方案1】:

我实际上在缓存问题中找到了解决方案。我在标题中使用了这段代码:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

并将其更改为:

<?php
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
?>

我不知道 HTML 版本的哪一部分出错了,但是 PHP 版本可以正常工作,从而解决了我的问题。非常感谢您的想法和意见!

【讨论】:

    最近更新 更多