Search code examples
phpsessioncookiessession-cookies

First time logging in in Incognito/InPrivate window doesn't set session or cookie


I'm not entirely sure yet whether this only affects incognito windows or also "fresh" normal browser windows (but clearing all browser cache doesn't reproduce the issue).

The issue is the following:

When I try to login to my PHP/HTML website, in an incognito window it looks like the SESSION and COOKIES aren't set the first time that I login. When I enter a username and password, I do get to the 'logged in' page, but when I click any link within the site, it redirects me to the login screen and printing $_SESSION or $_COOKIE shows empty values. The second time I log in, the SESSION and COOKIE are set like normal.

However, I can't figure out why this only occurs in Incognito/InPrivate tabs...

My login flow is as follows:

index.php:

<?php session_start(); 

if(!isset($_SESSION["userID"]) && !isset($_COOKIE["userID"])){
  include('login.php');
}

include('startup.php');

if(isset($user_data){

  // Show login screen

} else {

  // Show page with user logged in

}

?>

login.php:

<?php 

if(!empty($_POST["username"]) && !empty($_POST["password"]) && $_POST["action"]=="login"){ 

  // Here I check if the user exists and return $user_data and $user_found.

  if($user_found==1){

    $_SESSION["userID"]= $user_data["id"];
    session_start();
    setcookie("userID", $user_data["id"], time()+31536000);
    $_COOKIE["userID"]= $user_data["id"];

  } else {

    // User not found error

  }

}

?>

startup.php

<?php 

if(isset($_COOKIE["userID"])){
  $_SESSION["userID"]= $_COOKIE["userID"];
}

if(isset($_SESSION["userID"])){

  // Get userdata from database

  $user_data= mysqli_fetch_array( ... ); 

}

?>

I have tried extensive debugging (printing $_POST, $_COOKIE and $_SESSION at all stages through the login flow): in normal browser windows everything works fine (even with All Cache cleared), in Incognito/InPrivate windows the $_COOKIE and $_SESSION are correctly set when I log in, but when I refresh the page or load another page within the logged-in-section they are empty again.

Any help/suggestions would be greatly appreciated.


Solution

  • Figured out the problem: some JavaScript that I was loading in was ALSO generating a cookie with a PHPSESSID, thus overwriting the sessionID that was created by session_start() and logging me out. The second time, the sessionID generated by the javascript would still be there (thus session_start() would not create a new one) and logging in would work and I would stay logged in.

    Tip for anyone having similar problems: check the PHPSESSID cookie in the Developer Tools.