Edit: I just wasn't exiting after sending the header redirect.
When echoing a session value, inside of an output buffer of an include file, if the value is changed later in the script, the later value is the one echoed.
Our website uses an in house framework wherein each page is in its own file which gets included by index.php
. The index file captures the output of the include file in a buffer, and stores it to variable. It does some other things, then echos headers, footers, and the captured include file.
The issue is that the $_SESSION
behaves in an unexpected way when following a POST to GET pattern:
Post to a form, it sets something in the session, then do a get redirect to another page. On the redirected page, if you echo something from the session, then manipulate it AFTER the echo statement, the final result is that whatever is echo'd reflects the later change. The same goes for unset
; echo something from session, then unset
it, and the result is that it echos and empty string.
Here is a basic example:
form.php
if (!empty($_POST['string'])) {
$_SESSION['message'] = $_POST['string'];
header("Location: ./index.php?page=formHandler");
//EDIT - This was not in the original code
//exit;
} else {
?>
<form action="index.php?page=form" method="post">
<input type="text" name="string"><input type="submit" />
</form>
<?php
}
formHandler.php
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
$_SESSION['message'] = "changed";
}
index.php
session_start();
ob_start();
include $_GET['page'] . ".php";
$page = ob_get_clean();
echo $page;
So, what happens:
Starting at form.php (which is included by index)
Type in a value, post it.
The text "changed"
is always displayed, even though it is set after the echo
statement.
This is simplified for the sake of example; the header is triggered by rewrites, not get params, and a few other things, but the idea is there.
So my question is what is causing this unexpected behavior, and what can I do to fix it?
Using PHP 5.4