Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: session isn't saving before header redirect

I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database. My code is as follows:

// session
$_SESSION['userID'] = $user->id;        
header('Location: /subdirectory/index.php');

Then at the top of index.php after the session_start(), i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual (http://php.net/manual/en/function.session-write-close.php) and neither session_write_close or session_regenerate_id(true) worked for me. Does anybody know a solution?

Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script

like image 418
phpNutt Avatar asked Jun 03 '10 18:06

phpNutt


1 Answers

I haven't heard of this issue, but I haven't used sessions all that much.

With sessions you MUST do a few things and have a few setting setup:

  • cookies enabled on client side
  • session_start(), before anything happens
  • make sure you don't destroy the session(unless they want to logout)
  • The PHP session id must be the same (relates to cookies)

Another issue could be the $user->id is returning a reference to an object that doesn't exist on the next page. Most likely not, but make sure.

If I saw your code I could help you a lot more. But when debugging check the session key with session_id() and make sure it's the same. If you could try that then tell me I could keep helping.

I too would like to know how this ends up for when I get back into sessions.

like image 153
Michael Ozeryansky Avatar answered Oct 16 '22 20:10

Michael Ozeryansky