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

Posted on Feb 27, 2008 in PHP | 11 comments


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.