Php – CORS policy: No ‘Access-Control-Allow-Origin’ for JSON files

corshttphttp-headersPHP

I kept a JSON files in Server A, ip : 111.111.111.111/folder1/a.json

From Server B [ ip : 444.444.444.444 ], I am trying to access that JSON file , I received the result below:

Access to XMLHttpRequest at 'http://111.111.111.111/a.json' from origin 'http://444.444.444.444' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I wrote the following code in 111.111.111.111/index.php , but I am receiving the same error:

<?php

Access-Control-Allow-Origin: "http://444.444.444.444"
Access-Control-Allow-Origin: *
Header set Access-Control-Allow-Origin: *

?>

Accessing JSON using below JavaScript code :

$.getJSON("http://111.111.111.111/folder1/a.json", (data) => {  }

Best Answer

Your Access-Control policy needs to be set on the same URL than the requested ressource.

What I mean is that if you're going to request access to /folder1/a.json, then the Access-Control headers needs to be set on the requests for this specific URL.

You could add these headers via your server (Apache / Nginx / ...) or create a php script like the one you made that sets those headers and returns the json file content (i.e. /folder1/a.json.php).

BTW your code isn't valid PHP, use the header(...) function.

You coud use a script like this:

<?php
    header('Access-Control-Allow-Origin: http://444.444.444.444/*');
    header('Content-Type: application/json; charset=utf-8');
    die(file_get_contents('a.json'));
?>