如何使用 PHP 会话变量然后更改它?

发布于 2024-10-22 22:22:25 字数 672 浏览 5 评论 0原文

我遇到一种情况,我处理表单,如果会话变量中存在问题和错误消息,然后在标头重定向后回显。为了清除会话错误消息,我将其设置为 null;然而,这样做会导致它根本不会被回显。我的代码很长,但这里有一个演示该行为的示例。

整个文件:

<?php
session_start();

if($_REQUEST['set_session'] == 'true')
{

    $_SESSION['error_message'] = '<p>Should be this.</p>';

    header('Location: session_test.php');
}
?>
<html>
<head>
</head>
<body>

<?
echo $_SESSION['error_message'];

$_SESSION['error_message'] = '<p>Should not be this.</p>';

?>

<p><a href="session_test.php?set_session=true">Test</a></p>
</body>

有人可以解释为什么我得到“不应该是这个”而不是“应该是这个”吗?以及我如何才能得到我想要的结果。

I have a situation where I process a form, if there are problems put and error message in a session variable and then echo is out after a header redirect. To clear the session error message, I then set it to null; however, doing this causes it not to be echoed out at all. My code is quite long but here is an example that demonstrates the behaviour.

The whole file:

<?php
session_start();

if($_REQUEST['set_session'] == 'true')
{

    $_SESSION['error_message'] = '<p>Should be this.</p>';

    header('Location: session_test.php');
}
?>
<html>
<head>
</head>
<body>

<?
echo $_SESSION['error_message'];

$_SESSION['error_message'] = '<p>Should not be this.</p>';

?>

<p><a href="session_test.php?set_session=true">Test</a></p>
</body>

Can someone explain why I get "Should not be this" rather than "Should be this"? And how I might get the result I want.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无法言说的痛 2024-10-29 22:22:25

我认为如果您在标题后退出脚本,您的问题应该得到解决。使用这个:

header('Location: session_test.php');
exit();

即使浏览器转到另一个页面,脚本也会在调用 header 后继续运行。因此,虽然该页面中的回显没有显示,但错误消息仍然发生了变化。

I think your trouble should be fixed if you exit yourscript after the header. Use this:

header('Location: session_test.php');
exit();

The script goes on after the call to header, even if the browser goes to another page. So while the echo in this page is not shown, the error message is still changed.

厌倦 2024-10-29 22:22:25

header 重定向后,您必须退出,否则脚本将继续执行。

After a header redirect, you must exit, otherwise the script carries on executing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文