is there a delay in setting session variables? failing on first attempt only

I have a page, login.php, that processes a username and password and if successful it sets session variables and then redirects the user to home.php. The relevant part of login.php is here:

if ($pwdHash == $storedpass) {
            $success = true;
            $sessionStatus = session_status();
            if ($sessionStatus !== PHP_SESSION_ACTIVE) {
                session_start();
            }
            $_SESSION['user_id'] = $user;
            $_SESSION['logged_in'] = true;
            session_write_close();
            header('Location: http://www.examplesite.com/home.php');
            header("HTTP/1.1 303 See Other");
            die("redirecting");
        }

Then home.php tries to collect the session variable

$sessionStatus = session_status();
if ($sessionStatus !== PHP_SESSION_ACTIVE) {
    session_start();
}
$loggedIn = $_SESSION['logged_in'];

The problem is that on the first login attempt, $_SESSION['logged_in'] is undefined and generates an error, even though login.php was successful.

Notice: Undefined index: logged_in 

A var_dump of $_SESSION returns an empty array, but sessionStatus reports that the session was already started, it did not have to execute session_start.

This forces the user to log in a second time, then everything is fine. So is the redirect just happening too fast for the session variable to get set? Should I put a delay in the redirect? (and how would I do that?) Or is this something else that I'm doing wrong?

EDIT: I've checked with my host based on an answer to a similar question and confirmed that a session would never be served by more than one server and there is no need to enable sticky sessions or anything like that. I've also updated the code above based an answer offered below and some other research but the error persists.


Solution 1:

The session is probably automatically saved when the script ends. You redirect before the script ends.

How long your script takes to really end depends very much on what other code needs to wind down. It is better to explicitly save the session.

How to do this depends on what kind of sessions you use. One type can be closed like this:

http://php.net/manual/en/function.session-write-close.php

If that's the one you're using do this:

if ($pwdHash == $storedpass) {
  $success = true;
  $_SESSION['user_id'] = $user;
  $_SESSION['logged_in'] = true;
  session_write_close();
  header('Location: http://www.examplesite.com/home.php');
  header("HTTP/1.1 303 See Other");
  die("redirecting");
}

And the session should be available to the next page when you redirect.

If your sessions work differently, you have to adapt the code, of course. The point I'm trying to make is: Never put a delay in your code. It's unreliable, and pointless. Simply save the session before you redirect.