Q:

PHP & CORS (Cross-Origin): How does this work?

I have learned that you can add the following in a PHP script to allow Cross-Origin Requests:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Normally I would have added this to my .htaccess file, but the above is handy when I am testing Ajax without Apache. It certainly works when testing with php -S.
I would have thought that the timing is wrong. Shouldn’t the CORS request be accepted before the script runs? If so, how would PHP have the opportunity to decide whether add these headers?

A:

CORS checking is implemented by the client, when it receives the response. If the client and server are not in the same domain, the client checks the response to see if it contains the Access-Control-Allow-XXX headers appropriate to the request. If not, it ignores the response and reports an error.
So nothing prevents the PHP script from running. It can perform its own checks of the request headers and form parameters, and decide whether to allow the operation.

