-1

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 :

  1. If I comment the session_start(); line, it works and do the var_dump as expected.
  2. 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!

Simon Trichereau
  • 721
  • 11
  • 19
  • I believe that Fetch does not submit cookies by default. – TKoL Mar 17 '23 at 17:29
  • Does this answer your question? [Fetch API with Cookie](https://stackoverflow.com/questions/34558264/fetch-api-with-cookie) – TKoL Mar 17 '23 at 17:29
  • Is it definitely a same-origin request? – TKoL Mar 17 '23 at 17:31
  • @TKoL, it is the same-origin, my script is called on my-domain.com/index and it tryes to go to my-domain.com/tracking so yeah, it is the same domain. Btw I also tried with `credentials: "include"` and got the same result! – Simon Trichereau Mar 17 '23 at 18:33

1 Answers1

0

Ok I found my answer :

The problem was not about the cookies, but about the fetch !

I modified my code to add some manipulation on the answer in the fetch response and now it works fine !

So now my code looks like this :

const body = new FormData();
body.append('foo', "bar")
fetch(`/tracking`, {
    credentials: "same-origin",
    method: "POST",
    body,
    headers: { "Content-Type": "application/x-www-form-urlencoded" }
}).then(async r => await r.text())

And it appeared to work fine.

I presume that it's something due to browsers ?

Simon Trichereau
  • 721
  • 11
  • 19