php - 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();
有人可以解释一下为什么会这样吗?
解决方案
发生这种情况是因为您的浏览器在此脚本(您在上面显示的那个)实际将会话数据写入存储之前重定向到新页面。会话数据一直保存在内存中,直到脚本完成或您手动调用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();
这也意味着您的会话不会像您最初怀疑的那样“被重定向的速度更快”。
推荐阅读
- php - 通过 PHP 上传文件时完全忽略 .htaccess 参数
- reactjs - Flask-CORS 后端(在 Heroku 上)返回 HTML 文档而不是 JSON
- excel - VBA 帮助 - 如果一列包含特定字母,则将另一列设为负数,然后循环
- swiftui - 我可以将 QuickLook 与基于 SwiftUI 文档的应用程序一起用于我自己的文件类型来制作预览缩略图吗?
- c# - 如何使用 Object c# .NET Core 在 blob 存储 Azure 上创建 csv 文件?
- github - 我无法在 github 页面中设置自定义 subdomin
- spring-boot - 开放班次中用于 Spring Boot 微服务的 API 网关
- css - CSS网格防止孙子溢出滚动条
- python - 如何在 MySQL 8 中保存 phash 并计算汉明距离?
- typescript - 是否可以在 Typescript 中获取记录值的数组类型?