【问题标题】:Error when retrieving session_id() after redirecting to another page重定向到另一个页面后检索 session_id() 时出错
【发布时间】:2011-06-06 20:36:26
【问题描述】:

非常菜鸟的问题。

我想在 PHP 中使用 Post/Redirect/Get 模式开发一个登录表单。包含登录表单的页面是这样的:

<?php
  if (try_login()) {
    session_regenerate_id();
    session_start();
    header('Location: main.php');
    exit();
  }
?>
<html>
  <head>
    <!-- etc, etc -->
  </head>
  <body>
    <form action="<?php echo htmlentities($_SESSION['PHP_SELF']); ?>" method="post">
      <!-- etc, etc--></head>
    </form>
  </body>
</html>

出于调试目的,main.php 仅包含

<?php
  echo htmlentities(session_id());
?>

我希望在成功登录后被带到main.php 并显示我的session_id()。但是,当我自己测试登录表单时,我被重定向到main.php,但我的session_id() 没有出现。我的代码有什么问题?

【问题讨论】:

  • 除非您使用session.auto_start,否则您需要根据会话数据在所有页面上使用session_start()显式启动会话。
  • 请原谅我的语言不当,但是... 什么鬼?我是否必须使用session_start(),即使我实际上并没有开始,而是恢复会话?
  • 编程时不要假设,阅读文档。请记住,HTTP 是无状态的。这意味着服务器不知道您在上一页中调用了某些内容。它只知道它有一个页面请求。所以是的,在对会话进行任何操作之前,您必须调用 session_start() 。 php.net/manual/en/session.examples.basic.php

标签: php session redirect


【解决方案1】:

您需要在main.php 中调用session_start(),然后才能检索会话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-08
    • 2018-04-27
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多