search

Home  >  Q&A  >  body text

Set the $_POST variable to empty while using php://input to get everything correct

I created a React application from which I call a server built on PHP.

Here's how I call the PHP file:

const requestOptions = {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: JSON.stringify({ name, username, password }),
};
console.log(requestOptions);

fetch('http://localhost/crud/requests/signup.php', requestOptions)
  .then(res => res.json())
  .then(data => console.log(data));

This is what I have in the PHP file:

if (isset($_POST) && !empty($_POST)) {
  // do something
}

When I print the $_POST variable, I get an empty array. Even $_RESPONSE is empty.

But when I try to print the input stream like this:

print_r(file_get_contents('php://input'));

Everything seems fine. Can anyone explain why this happens? I tried reading it in the documentation and looking up some forums and blogs, but wasn't satisfied with the answers.

P粉032649413P粉032649413245 days ago344

reply all(1)I'll reply

  • P粉718165540

    P粉7181655402024-03-28 13:41:16

    PHP's built-in form support can only parse the application/x-www-form-urlencoded form and the multipart/form-data form. What you are actually sending is a JSON serialized object with a MIME type of application/x-www-form-urlencoded.

    To actually send the application/x-www-form-urlencoded form, use URLSearchParams instead of JSON .stringify

    fetch('http://localhost/crud/requests/signup.php', {
      method: 'POST',
      body: new URLSearchParams({ name, username, password }),
    })
    .then(res => res.json())
    .then(data => console.log(data));
    

    In this case, there is no need to explicitly set Content-Type: The browser does this automatically. To send a multipart/form-data payload (which you may need to do if you want to upload larger files), use a FormData object.

    If you ultimately want to send JSON, you should send it using the correct MIME type in the header, application/json. On the PHP side you will have to use json_decode.

    reply
    0
  • Cancelreply