Set the $_POST variable to empty while using php://input to get everything correct
P粉032649413
P粉032649413 2024-03-27 19:30:45
0
1
337

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粉032649413
P粉032649413

reply all(1)
P粉718165540

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手动解析有效负载>.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template