Why do i lose my session variable after a redirect with header()

What would cause a session variable to be unset or not available after a redirect? for example, below is a snippet of code i’m working with. if exit() was not commented, it would display the variable I’m looking for. but once php hits header() and the next page loads $_SESSION[‘flash’] is null ( or, at least when I use print_r() on index.php this is displayed for flash - with no value: [flash] => ). I am starting a session on index.php.

Thanks in advance



            if($_SESSION['flash'] == null){
                if(isset($insert)){
                    $_SESSION['flash'] = "<p>message 1</p>";
                } else {
                    $_SESSION['flash'] = "<p>message 2</p>";
                }
            }
            
            //exit($_SESSION['flash']);

            switch($_POST['submitted']){
                case "Save > Finished":
                    header("Location: index.php");
                    break;
                default:
.
.
.
.

            }

Does index.php have a session start statement at the top?

it has this at the top: require_once(‘checkSession.php’);

and the first line in checkSession.php is a session start statement

Even with a redirect the script will still process. By default the session data is not going to be written until the very end. So assuming the data isn’t available may mean that the previous script hasn’t completed executing before the reference is made in the redirect script. The way you could check this is the case is to write the session manually before redirecting or exit which will completely kill the script and write the session.

session_write_close()

See if adding that right before the redirect fixes the issue, though the exit would probably be a better approach.

Running a search on header( for that page yielded this, so I could be wrong with my suggestion.

Make sure there is a die(); immediately after the redirect statement because otherwise the original php script will still continue to execute in the background whatever code there might be after the redirect. This could be causing a problem with your session.

Another option could be to use session_write_close()

edit: just noticed this is essentially what oddz suggested

thanks for the help! die(); right after the redirect worked. I did not realize that the current php script continues to run after header()… this issues makes sense then because many many lines later I’m including another file that checks $_SESSION[‘flash’] and sets it to null. thanks again.