phpsessionsession-variables

When one script creates multiple XHRs to the same PHP file, are you creating multiple sessions or just one session?


Apologies if this seems like a repeat question but I'm having a different doubt now.

Basically I have a PHP file that is set up like this:

<?php

session_start();
$_SESSION['globalVar'] = "undefined";

if (!empty($_POST['triggerLoop'])) {

    for ($x = 0; $x < 5; $x++) {
        $_SESSION['globalVar'] = getResult();
        sleep(1);
        
    }
}


//------------------------------------------------------
//Listen
if (!empty($_POST['listen'])) {

    echo  $_SESSION['globalVar'];
}

function getResult()
{
    return rand(10, 100);
}

?>

Pretty straight forward. It is supposed to update a global variable (globalVar) from inside a loop every 1 second, using a random int.

I have a script.js file which creates seperate XmlHttpRequests to this php file. The first request will trigger the loop (which updates globalVar).

Immediately after that, script.js will start an interval where it will start sending new XHRs to the php file every second and attempt to read the value of globalVar.

function postToHandler(){
    console.log("Posting to handler");

    let xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    xhr.open("POST", "./apps/researcher.php");

    let form = new FormData();
    form.append('triggerLoop', "mockData");

    xhr.send(form);

    activateGlobalsListener();
}


function activateGlobalsListener(){
    
    setInterval(function(){
        let xhr_listen = new XMLHttpRequest();
        xhr_listen.withCredentials = true;
        xhr_listen.open("POST", "./apps/researcher.php");

        let form = new FormData();
        form.append('listen', "mockData");
        xhr_listen.send(form);

        xhr_listen.onreadystatechange = function (){

            if(xhr_listen.readyState === XMLHttpRequest.DONE){
                console.log("RECEIVED LISTEN DATA");
                console.log(xhr_listen.response);
            }
        }

    },1000);
}

I was expecting the XHRs in the setInterval to return random ints, but they always return "undefined".

Which makes me wonder if this is happening because the XHRs are creating their own unique sessions? As in, the first XHR creates session#1. And then the subsequent XHRs create session#2...session#3...etc. And that's why those subsequent XHRs are not able to access the global variables of session#1? Because they are existing on different sessions?


Solution

  • It looks as though you are resetting your session variable to "undefined" every time you call the file regardless of whether it is a "triggerLoop" request or a "listen" request.

    You likely just need to move the variable reset inside the triggerLoop conditional:

    <?php
    session_start();
    
    if (!empty($_POST['triggerLoop'])) {
    
        $_SESSION['globalVar'] = "undefined";
        for ($x = 0; $x < 5; $x++) {
            $_SESSION['globalVar'] = getResult();
            sleep(1);
            
        }
    }
    //... script continues as before
    

    Note, you still have a race condition here since you are doing setInterval in the JS and also doing sleep(1) in the php, so don't necessarily expect to get 5 random numbers (you might just get the first 3-4 numbers being different and then the same number over and over). This looks like you're just testing functionality so it likely isn't a problem in your real use case, but something to be aware of.