Reply to comment

strict warning: Only variables should be passed by reference in /mnt/volume-sfo2-01/www/ on line 559.

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.


The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

4 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.