1

PHP cannot read a cookie set by JavaScript. Although the. PHP file is in a separate folderript file, they are on the same domain. When I set the cookie in JavaScript, I use fetch to call the PHP file. However, when the call is made, PHP cannot see any cookies. I can see the script running successfully in the network console.

Javascript:

document.cookie = "name=value0;";

fetch("/path/to/file.php", {
      method: "POST",
      credentials: "same-origin",
      body: JSON.stringify({
        value1: value1,
        value2: value2
      }),
      headers: {
        "Content-Type": "application/json"
      },
    });

PHP:

var_dump($_COOKIE);

PHP response:

array(0) {
}
10
  • You are setting your cookie in the document. However, your fetch doesn't send the document or know about your cookie. You should set your cookie in the fetch itself. Check this question/answer stackoverflow.com/questions/34815845/… Commented Apr 8, 2024 at 22:58
  • @RAllen That question is about node-fetch, not fetch in the browser. Commented Apr 8, 2024 at 23:00
  • If you examine the headers of the request in DevTools->Network, do you see the cookie being sent? Commented Apr 8, 2024 at 23:01
  • @Barmar When I click "show filtered out request cookies" in Chrome, then I can see the cookie. But when I uncheck the box it says "No request cookies were sent." Commented Apr 8, 2024 at 23:04
  • 1
    try adding an appropriate Path to the cookie Commented Apr 8, 2024 at 23:16

1 Answer 1

1

Thanks you Barmar and JaromandaX!

The proper code is:

document.cookie = "name=value0; path=/;";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.