首页 > 解决方案 > session_destroy() 比我需要的早执行

问题描述

所以我有这样的代码:

$_SESSION['message'] = "Some Message";
$MSG = $_SESSION['message'];
header('location: ../Pages/Error.php');
echo "<script type='text/javascript'>alert('$MSG');</script>"; //It has text here
die(); //i set this only for testing purpose
session_destroy();
die();

正如您在上面看到的那样,我有 2 个die()- 第一个是用于此测试目的。

因此,当代码是第一个die()并且echo()../Pages/Error.php使用的时候$_SESSION['message']通常会显示该消息,因为内部Error.php文件和alert(这也是出于测试目的)但是当我出于某种原因删除这两个时,sesion_destroy();运行速度比header()函数快,并且 id 破坏了我$_SESSION['message'],所以我Error.php显示空消息。

没有测试部分的代码:

$_SESSION['message'] = "Some Message";
$MSG = $_SESSION['message'];
header('location: ../Pages/Error.php');
session_destroy();
die();

有人可以解释一下为什么会这样吗?

标签: phpsession

解决方案


发生这种情况是因为您的浏览器在此脚本(您在上面显示的那个)实际将会话数据写入存储之前重定向到新页面。会话数据一直保存在内存中,直到脚本完成或您手动调用session_write_close() 。

这意味着要让您的示例正常工作,您必须在输出重定向标头之前编写会话数据,如下所示:

$_SESSION['message'] = "Some Message";
$MSG = $_SESSION['message'];
session_write_close();
header('location: ../Pages/Error.php');
echo "<script type='text/javascript'>alert('$MSG');</script>"; //It has text here
die(); //i set this only for testing purpose
session_destroy();
die();

这也意味着您的会话不会像您最初怀疑的那样“被重定向的速度更快”。


推荐阅读