javascript - Set and get session variables in PHP through fetch API
one text
I am trying to set a session variable using fetch -
const response = await fetch('http://locahost/index.php/session/set', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({token:"token"})
});
The PHP function (inside a class) that does this -
public function setSession($arr){
try{
session_start();
$_SESSION['token'] = $arr['token'];
$responseData = json_encode("SESSION token has been set to ".$_SESSION['token']);
/// sendresponsedata() -> send response back with Access-Control-Allow-Credentials: true
} catch (Error $e) {
/// Some error
}
}
The PHP function is not on the same page as the page making the fetch request. When I console.log the response on the page that sent the request, it correctly shows SESSION token has been set to token
.
But if then I try to retrieve the session variable using a different request and a different function -
fetch('http://localhost/index.php/session/get',{
credentials: 'include'
})
The response I get from this is always No ongoing session
public function getSession(){
try {
session_start();
// print json_encode($_SESSION); <---- printing this shows an empty array
$responseData = json_encode((isset($_SESSION["token"])) ? $_SESSION["token"]:"No ongoing session");
/// sendresponsedata() -> send response back with Access-Control-Allow-Credentials: true
} catch (Error $e) {
/// Some error
}
}
I looked at other questions like mine but as far as I could understand, the error was because of not allowing credentials. I couldn't really understand why credentials are needed in this case reading this, but I added them anyway to check first, but that didn't change anything. As far as I could understand fetch request creates a new session everytime so this could be impossible, but this might be possible if I made an AJAX request. I am not sure I understood that correctly however.
The sendresponsedata()
function works well as I have made many other fetch requests with more headers, like allowing cross-origin requests and returning required headers on preflight handshakes which all worked (and it is not really a complicated function).
What am I doing wrong and how can I achieve what I need?
Edit: Since posting I have also tried xhr requests and they don't work either.
Source