NYCPHP Meetup

[nycphp-talk] Disappearing $_SESSION variables after using header ()

David Krings ramons at gmx.net
Tue Nov 25 06:45:01 EST 2008


Tony Furnivall wrote:
> I now have that part of things working fine. However, because there is 
> an implicit exit; after issuing the call to header (), I'm uncertain if 
> the $_SESSION variables are being set properly.
> 
> When I trace them at the end of one page they are all there 
> ($_SESSION['userid'] = $userid; $_SESSION['badgename']=$badgename;), but 
> when I examine the $_SESSION array at the start of the next page, the 
> variables do not exist. My guess is that by short-circuiting any nrmal 
> end-of-script processing, I may be bypassing the write of the $_SESSION 
> array to the temporary file. This feels like forcing a buffer-flush when 
> working with low-level disc IO. Is there any known reason for $_SESSION 
> variables to disappear in such circumstances?
> 
> Does anyone have any other ideas?

I use the header() redirect frequently in combination with sessions. What I 
found to be a mandatory must at all times is to execute session_start(); at 
the very beginning of any script working with the session variable. Do that 
before including any files, setting anything, or executing any code. That 
always did the trick for me. Doing it a few lines further down when it would 
make logical sense often caused that the session was gone, even when 
referencing the session_ID.
Also, and I think that is in one of the annotations on php.net for header(), 
when using the header() redirect explicitly write the values to the session 
(of course I forgot the command for that). At times the redirect is completed 
before the session is written out and with a new request coming in the PHP 
interpreter gets confused as to what belongs where.

David



More information about the talk mailing list