All in the <head> – Ponderings and code by Drew McLellan –

PHP Sessions Update

If you read Sessions, hah! What are they good for you would have noticed that I was having intermittent problems with session variables in PHP (on Windows – yuck). Thanks for all the helpful comments.

I finally tracked down the problem, and discovered a solution to boot. It would seem that if you set a session variable and then later in your script redirect to a different page, the session variable will sometimes get lost. I can see the logic of this in as far as setting a cookie and then modifying the headers – it’s a reasonable side affect that the cookie might get lost – but why is it intermittent? I thought computers were supposed to be deterministic.

Anyway, if you’re going to set a session variable and then redirect, best to close the session object first:

$_SESSION[‘foo’] = $bar;
session_write_close();

header(“Location: http://example.com/”);
exit;