If call PHP page via ajax that takes a while to run/return (and it sets session variables), will a 2nd ajax call see those session changes?

后端 未结 1 1417
甜味超标
甜味超标 2021-01-24 18:13

I have a front end script that calls a PHP page via ajax. That PHP page can run for 20-30 seconds. During its run, it sets a $_SESSION variable multiple times to in

1条回答
  •  没有蜡笔的小新
    2021-01-24 19:04

    I think it will depend on whether the first script had to create the session, or it was already created before the first script was run. To continue a session, the client has to have received a response from a script that sends the session ID cookie. So the first requirement is that the session be started by some script that completes before you send the first AJAX request. This could be the script that sends the page that contains the AJAX calls.

    Another issue is that PHP normally locks the session file when the session is opened, and updates it when a script terminates. So if a second script tries to access the same session while the first script is running, it will hang waiting for the lock. To force it to update immediately and unlock the file after assigning a session variable, you need to call session_write_close(). And after closing the session file, you need to reopen it again with session_start() before writing to the session variable.

    //Start
    $_SESSION[ "status" ] = "started";
    session_write_close();
    
    //Some long function
    doSomethingSlow();
    
    //Progress
    session_start();
    $_SESSION[ "status" ] = "did something";
    session_write_close();
    
    //Some long function
    doSomethingElseSlow();
    
    //Done
    session_start();
    $_SESSION[ "status" ] = "started";
    session_write_close();
    

    0 讨论(0)
提交回复
热议问题