27 Feb

Session variables not set on following page after header() redirect

The main reason for this blog here is to share with others the problems I’ve encountered and solved in the hope of saving someone banging their heads on the wall trying to solve issues that are sometimes trivial but waste stupid amounts of time.

A problem I recently encountered is that after doing some PHP magic and then redirecting a user to another page, the following page loses all the session information set in the previous page. For hours I was there trying to figure out why this was happening, and hopelessly trawling the net for answers!

Finally, it occurred to me that all pages that had this problem were using header(’Location : …’) redirects.

“Okay, so what? I set the session variable and that should be that.”

Well, I agree, but for some reason, this doesn’t quite cut it, and without an exit() or die() statement right after session variables are not saved. In hindsight, this is quite a reasonable approach anyway, as in many cases (although not in mine) you probably don’t want the script to carry on anyway, so terminating it would be useful.

If you liked this post, why not share it?

  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit
  • RSS
  • StumbleUpon
  • Technorati
  • Twitter

Related Posts

  • Do search engines index the same page more than once?
  • Sandro
    Thanks man, you just solved problem and reached the goal of this post. You made me save stupid time fixing a stupid problem!

    Thanks again!
  • No problem, that's what it's all about!
  • chris
    Thank you very very much!
  • asdf
    So if I exit() or die() after the redirect(Location: ...) the session values are retained? Not working for me.
  • You still have to do the usual to start a session - session_start(); and also set variables etc.

    This is to make sure session data is saved in the event of a redirect.

    If that's not working, it's most likely a bug in your code.
  • Thanks, this saved me a lot of time.
blog comments powered by Disqus