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.
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.
After a header
redirect, you must exit
, otherwise the script carries on executing.
精彩评论