Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

I have experienced the same issue while writing the session content to the database. To make it work I have added the sleep() function before setting the session variable, just like below.

sleep(2);
$_SESSION['GUID'] = uniqid(time().rand());

It resolves the issue for me.

We have observed this issue when the page hits are frequent but if one or two users are accessing the page it works as expected.

about 4 years ago · Santiago Trujillo Report

0

I have encountered this same issue with a login page but none of the suggestions work for me. The only thing I've found that does work is redirecting the page to itself after 1 second and then checking the session variables to see if the login was successful...

startSession(); // assigns all the login session variables, etc.
header('Refresh: 1; URL=/[THIS_PAGE].php'); // [THIS_PAGE] = the current login page

However, this is a very inelegant solution and I don't like using it. But it "works".

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!