Instant Cross-Domain Access for Everyone with CORS in PHP

Here’s a snippet of code that will make your PHP REST API work cross-domain, through the magic of CORS:

 * CORS is a way to allow scripts from other domains to post to this URL.
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Origin: *');

[Edit: I just found out this is an error. When the request method is not options, you should send back the origin in the Access-Control-Allow-Origing header.]

Put that somewhere near the top of your script.

Note that the last line is put there so all other requests will have a CORS header that allows access. You need that header on the POST response, too.

Also note that you may need to allow the GET method, or other methods, if that’s how your API works.

If you’re using a framework, read the docs before using this hack. There are probably libraries out there. An interesting CORS story. I don’t agree with the conclusion: OPTION should always be supported. Headers seem to be used a lot with content negotiation. Also see this SO thread: What’s the point of x-requested-with header.