5

I'm losing the data in $_SESSION when I do a header redirect. When I walk through this with a debugger I can see all my data in $_SESSION before I exit();

Login.php :

...

if($result == 1){       
    header("Location: /myaccount.php");
    session_write_close();
    exit();
} else {
    header("Location: /login.php?invalid=yes");
    exit();
} 

Then I put a breakpoint after the session_start() conditional below and $_SESSION is completely empty.

myaccount.php:

<?php
if(!isset($_SESSION['user_id'])) { session_start(); }

$docRoot = getenv("DOCUMENT_ROOT");
...

Where did my session go?

3 Answers 3

7

Make sure you are using the function session_start(); before the if-statement on myaccount.php

Sign up to request clarification or add additional context in comments.

2 Comments

Well this was kind of the problem. I use that conditional on every page so that I don't try to call session_start() multiple times. There's always a user id in the session so that test works fine.. as long as I type it in right. It's actually 'userid'. Dumb mistake. Is there a way to just delete this worthless post?
@sing1ejack: don't delete the post, it maybe useful for someone who faces the same problem. I was happy seeing your post, but I thought it's a bit more complex than forgetting the session_start();. :D In my case, it also doesn't work after header redirection, but I call session_start() every time I want to use $_SESSION variables, I set one in a file ($_SESSION['message'] = 'blahblah';), and when redirecting to another file with header(), $_SESSION array is empty. I also have redirected the session's save path to another directory, in which I can see the 'blahblah' message with text editor...
1

You should call session_start() on every page accessing (that is, reading or writing) $_SESSION, and call it before any access to the session array. So, be sure you call session_start() on both pages.

Comments

1

Yes don't delete post ... I had EXACTLY the same issue, and this post caused me to involuntarily smack palm firmly against forehead. And it fixed the problem (with my code that is, not my dumbness). Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.