matfr
matfr

Reputation: 109

How do you use a PHP session variable and then change it?

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.

Upvotes: 2

Views: 680

Answers (2)

Andrei Serdeliuc ॐ
Andrei Serdeliuc ॐ

Reputation: 5878

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

Upvotes: 0

Nanne
Nanne

Reputation: 64399

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.

Upvotes: 3

Related Questions