title: During Login with Facebook process, why are $_SESSION variables set via AJAX not being recognized as being set?
body: <p>I'm setting up Login with Facebook (using Javascript SDK) and it's working for the most part, with one strange exception I'm hoping someone can help me with.</p>
  
  <p>fb-login.php (full code below) has the Login with Facebook button.  User clicks that and it gathers data from Facebook and then uses AJAX to send the data to fb-login-process.php (full code below).</p>
  
  <p>On fb-login-process.php, some database updates/inserts are made depending on various scenarios (all of them are happening properly) and then I set two $_SESSION variables to allow them to be logged in, i.e. this part...</p>
  
  <pre><code>//set session variables so we can log them in
  $_SESSION['adminid'] = $adminid;                            
  $_SESSION['loggedinuser']="yes";
  </code></pre>
  
  <p>So back on fb-login.php, this is what triggers the AJAX request to fb-login-process.php and the subsequent redirect to a page on my app (/my-pools)...</p>
  
  <pre><code>if (response.authResponse) {
      // Send user data to database via AJAX
      getFbUserData();
      //redirect user to /my-pools (i.e. log them in)
      window.location.replace("/my-pools");
  }
  </code></pre>
  
  <p>Here's what happens.  Facebook login works fine and the database tables are updated/inserted properly.  The $_SESSION variables mentioned above are also set properly (more on this in a minute).  The redirect to /my-pools also works properly, however, on the /my-pools page I have this bit of code at the top of the page (to make sure user is logged in AND an adminid exists...i.e. those $_SESSION variables mentioned above)...</p>
  
  <pre><code>&lt;?php 
  if (isset($_SESSION['loggedinuser']) &amp;&amp; isset($_SESSION['adminid'])) {
      //continue
  } else {
      redirect_to('/');
  }
  ?&gt;
  </code></pre>
  
  <p>It keeps redirecting to /, so as far as that bit of code on /my-pools is concerned, one or both of those things is NOT set.</p>
  
  <p>However, I added code on / to echo those two $_SESSION variables and they BOTH echo actual values (i.e. they are actually set).  </p>
  
  <p>So why is it redirecting me?</p>
  
  <p>Furthermore, after getting redirected to / and seeing the properly echoed/clearly set $_SESSION variables, if I then manually change the URL to /my-pools it goes there properly and stays there.</p>
  
  <p>I hope this makes some sense to someone (if you need any clarification on anything, please let me know).</p>
  
  <p>In a nutshell, it appears that the $_SESSION variables are absolutely set, but that code above which checks if they're set doesn't agree/doesn't pass ON THE FIRST TRY ONLY. If try to go right back to /my-pools immediately after it didn't pass, it then does pass and stays on /my-page.</p>
  
  <p>So strange.</p>
  
  <p>Any ideas?</p>
  
  <p><strong>fb-login.php</strong></p>
  
  <pre><code>&lt;?php
  require_once("includes/session.php");
  require_once("includes/connection.php");
  require_once("includes/functions.php");
  
  ?&gt;
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"/&gt;
  &lt;link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet"&gt;
  &lt;meta name="robots" content="noindex,follow"&gt;
  &lt;title&gt;FB Login&lt;/title&gt;
  &lt;link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" /&gt;
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script&gt;
  
  window.fbAsyncInit = function() {
      // FB JavaScript SDK configuration and setup
      FB.init({
        appId      : 'XXXXXXXXXXXXXXXX', // FB App ID
        cookie     : true,  // enable cookies to allow the server to access the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.8' // use graph api version 2.8
      });
  
      // Check whether the user already logged in
      FB.getLoginStatus(function(response) {
          if (response.status === 'connected') {
              //display user data
              getFbUserData();
              window.location.replace("/my-pools");
          }
      });
  };
  
  // Load the JavaScript SDK asynchronously
  (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
  
  // Facebook login with JavaScript SDK
  function fbLogin() {
      FB.login(function (response) {
          if (response.authResponse) {
               // Send user data to database via AJAX
              getFbUserData();
              //redirect user to /my-pools (i.e. log them in)
              window.location.replace("/my-pools");
          } else {
             /* document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';*/
          }
      }, {scope: 'email'});
  }
  
  
  
  // Logout from facebook
  /*
  function fbLogout() {
      FB.logout(function() {
          document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
          document.getElementById('fbLink').innerHTML = '&lt;img src="fblogin.png"/&gt;';
          document.getElementById('userData').innerHTML = '';
          document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
      });
  }
  */
  
  
  // Save user data to the database
  function saveUserData(userData){
      $.post('fb-login-process.php', {oauth_provider:'facebook',userData: JSON.stringify(userData)}, function(data){ return true; });
  } 
  
  // Fetch the user profile data from facebook
  function getFbUserData(){
      FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
      function (response) {
          /*document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
          document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
          document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
          document.getElementById('userData').innerHTML = '&lt;p&gt;&lt;b&gt;FB ID:&lt;/b&gt; '+response.id+'&lt;/p&gt;&lt;p&gt;&lt;b&gt;Name:&lt;/b&gt; '+response.first_name+' '+response.last_name+'&lt;/p&gt;&lt;p&gt;&lt;b&gt;Email:&lt;/b&gt; '+response.email+'&lt;/p&gt;&lt;p&gt;&lt;b&gt;Gender:&lt;/b&gt; '+response.gender+'&lt;/p&gt;&lt;p&gt;&lt;b&gt;Locale:&lt;/b&gt; '+response.locale+'&lt;/p&gt;&lt;p&gt;&lt;b&gt;Picture:&lt;/b&gt; &lt;img src="'+response.picture.data.url+'"/&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;FB Profile:&lt;/b&gt; &lt;a target="_blank" href="'+response.link+'"&gt;click to view profile&lt;/a&gt;&lt;/p&gt;';
  */
          // Save user data
          saveUserData(response);
      });
  }
  
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;!-- Display login status --&gt;
  &lt;div id="status"&gt;&lt;/div&gt;
  
  &lt;!-- Facebook login or logout button --&gt;
  &lt;a href="javascript:void(0);" onclick="fbLogin()" id="fbLink"&gt;&lt;img src="fblogin.png"/&gt;&lt;/a&gt;
  
  
  &lt;!--&lt;div class="fb-login-button" data-max-rows="1" data-size="medium" data-button-type="continue_with" data-show-faces="false" data-auto-logout-link="false" data-use-continue-as="false" onlogin="fbLogin();"&gt;&lt;/div&gt;--&gt;
  
  &lt;!-- Display user profile data --&gt;
  &lt;div id="userData"&gt;&lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>fb-login-process.php</strong></p>
  
  <pre><code>&lt;?php
  require_once("includes/session.php");
  require_once("includes/connection.php");
  require_once("includes/functions.php");
  
  $createddate = date("Y-m-d");
  
  //Convert JSON data into PHP variable
  $userData = json_decode($_POST['userData']);
  if(!empty($userData)){
      $oauth_provider = $_POST['oauth_provider'];
      //Check whether user data already exists in social_users table
      $sql = "SELECT * FROM social_users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData-&gt;id."' LIMIT 1";
      $checkforsocial = mysqli_query($connection, $sql);
      if (!$checkforsocial) {
      die("Database query failed: " . mysqli_error());
      } else {
          if(mysqli_num_rows($checkforsocial) &gt; 0){ //user info already exists in social_users
              //Update user data      
              $sql = "UPDATE social_users SET first_name = '".$userData-&gt;first_name."', last_name = '".$userData-&gt;last_name."', email = '".$userData-&gt;email."', gender = '".$userData-&gt;gender."', locale = '".$userData-&gt;locale."', picture = '".$userData-&gt;picture-&gt;data-&gt;url."', link = '".$userData-&gt;link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData-&gt;id."'";
              $updatesocialusers = mysqli_query($connection, $sql);
              if (!$updatesocialusers) {
              die("Database query failed: " . mysqli_error());
              } else {
              }
  
              //should always exist but we'll check anyway in administrators table to see if email already exists
              $sql = "SELECT adminid FROM administrators WHERE email='".$userData-&gt;email."' LIMIT 1";
              $checkforemail = mysqli_query($connection, $sql);
              if (!$checkforemail) {
              die("Database query failed: " . mysqli_error());
              } else {
                  $row=mysqli_fetch_array($checkforemail);
                  $adminid=$row['adminid'];
              }
  
              //set session variables so we can log them in
              $_SESSION['adminid'] = $adminid;                            
              $_SESSION['loggedinuser']="yes";
  
  
          } else {  //user has not logged in via facebook before
              //Insert user data into social_users table  
              $sql = "INSERT INTO social_users (oauth_provider, oauth_uid, first_name, last_name, email, gender, locale, picture, link, created, modified) VALUES ('facebook', '".$userData-&gt;id."', '".$userData-&gt;first_name."', '".$userData-&gt;last_name."', '".$userData-&gt;email."', '".$userData-&gt;gender."', '".$userData-&gt;locale."', '".$userData-&gt;picture-&gt;data-&gt;url."', '".$userData-&gt;link."', '".date("Y-m-d H:i:s")."', '".date("Y-m-d H:i:s")."')";            
              $insertsocialusers = mysqli_query($connection, $sql);
              if (!$insertsocialusers) {
              die("Database query failed: " . mysqli_error());
              } else {
                  $social_users_id=mysqli_insert_id($connection);
              }
  
              //check administrators table to see if email already exists
              $sql = "SELECT adminid FROM administrators WHERE email='".$userData-&gt;email."' LIMIT 1";
              $checkforemail = mysqli_query($connection, $sql);
              if (!$checkforemail) {
              die("Database query failed: " . mysqli_error());
              } else {
                  $row=mysqli_fetch_array($checkforemail);
                  $adminid=$row['adminid'];
                  if (mysqli_num_rows($checkforemail) &gt; 0) {  //email already exists, so add social_users id to administrators table to link it to social account
                      $sql = "UPDATE administrators SET social_users_id = '".$social_users_id."' WHERE email = '".$userData-&gt;email."'";
                      $updatesocialusers = mysqli_query($connection, $sql);
                      if (!$updatesocialusers) {
                      die("Database query failed: " . mysqli_error());
                      } else {
  
                      }
  
                      //set session variables so we can log them in
                      $_SESSION['adminid'] = $adminid;                            
                      $_SESSION['loggedinuser']="yes";
  
                  } else {  //email doesn't exist, so need to make an entry for them in the administrators table
                      // first create adminid
                      $mmdd=date('md');
                      $year=date("Y");
                      $lastdigitofyear=substr($year, -1);
                      //create random identifier for rest of poolid to help with uniqueness
                      $seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
                      shuffle($seed); // probably optional since array_is randomized; this may be redundant
                      $rand ='';
                      foreach (array_rand($seed, 4) as $k) $rand .= $seed[$k];
                      $adminid="A".$mmdd.$rand.$lastdigitofyear."EN";
                      //now insert data into administrators table
                      $sql = "INSERT INTO administrators (adminid, social_users_id, firstname, lastname, email, createddate) VALUES ('".$adminid."', '". $social_users_id."', '".$userData-&gt;first_name."', '".$userData-&gt;last_name."', '".$userData-&gt;email."', '".$createddate."')";
                      $insertsocialusers = mysqli_query($connection, $sql);
                      if (!$insertsocialusers) {
                      die("Database query failed: " . mysqli_error());
                      } else {
                      }
                      //set session variables so we can log them in
                      $_SESSION['adminid'] = $adminid;                            
                      $_SESSION['loggedinuser']="yes";
                  }
  
              }
          }
  
  
          //send confirmation email here??????
  
          //log them in
  
      }
  } else {
  }
  ?&gt;
  </code></pre>