I have a small problem with my PHP application. I already have a session management working but there is a route I want to access with fetch from my front and it seems the session doesn't work.
This is the code in my file /tracking.php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if($_POST['foo'] ?? false) {
$_SESSION["foo"] = $_POST['foo'];
}
else {
unset($_SESSION['foo']);
}
}
http_response_code(204);
die();
this is the fetch i do from the front :
const body = new FormData();
body.append('foo', "bar")
fetch(`/tracking`, {
credentials: "same-origin",
method: "POST",
body,
headers: { "Content-Type": "application/x-www-form-urlencoded" }
})
but, when I watch in the network tab of my console, the request didn't do nothing. The preview is blank, I have a 200 answer from the back but the session isn't kept.
So, to debug, I modified the tracking.php
to this:
<?php
session_start();
var_dump($_POST["foo"]);
die();
And it still doesn't work, BUT :
- If I comment the
session_start();
line, it works and do the var_dump as expected. - If i modify the front to send a form instead of a fetch (cf the next block code) it works
const form = document.createElement('form')
form.method = "POST"
form.action = "/tracking"
form.innerHTML = `<input type="hidden" name="foo" value="bar">`
document.body.appendChild(form)
form.submit()
form.remove()
The point is I really need to use the fetch api, I can't perform a form send, do you have any idea why it doesn't work ?
Thanks for your help!