Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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.

over 4 years ago · Santiago Trujillo Denunciar

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.

over 4 years ago · Santiago Trujillo Denunciar

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".

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda