Home > Back-end >  PHP POST not adhering to .htaccess server CORS policy
PHP POST not adhering to .htaccess server CORS policy

Time:09-30

I am trying to set up a sandbox API for development, so users can hit the API from local dev machines. But am running into what I believe is a CORS issue.

At first all traffic was being blocked by the CORS policy, so I added the following to my .htaccess file:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

After that, I can see that not only am I getting a 200 status, but my payload is being correctly sent. Good stuff!

enter image description here
enter image description here

However .. The PHP file that is requesting -> /myp/index.php contains ONLY the following:

<?php
print_r ($_POST);
echo "Done";

And the response from the above POST comes back:

Array
(
)
Done

I have read MANY posts that all say the same thing: Add the following to the PHP file:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, X-Auth-Token, Accept");
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");

But when I add that to the PHP file .. I get another CORS error..

WITH CORS RULES APPLIED TO PHP FILE enter image description here

What else do I need to be looking at? Why is CORS denied when I throw the PHP headers in, but is OK without them? And why does PHP not accept the POST variables when CORS shows a 200 and I can verify post data sent?

CodePudding user response:

And the response from the above POST comes back:

The key there is that you do get the response and you don’t get a CORS error.

So the problem isn’t CORS and you shouldn’t touch your CORS headers.

(When you add the headers with PHP, Apache merges them with the headers you tell it to add and you end up with Access-Control-Allow-Origin: *, * which, as the error message says, is invalid).


If the $_POST superglobal is empty, it is because you aren’t POSTing data in a format that PHP will decode automatically.

Most likely, you are sending a JSON payload in which case you need to either read the body from STDIN and parse it yourself or change the data you are sending to be in a format that PHP does support (URL Encoded or Multipart Encoded).

const body = new URLSearchParams({ foo: 1, bar: "hello, world" });
const url = "http://example.com";
const response = await fetch(url, { body });
  • Related