0

I am trying to get CORS to work on my PHP and it is not working. I only want certain domains to have access to my php file. I have looked at other articles on Stackoverlflow (ie Cross-Origin Request Headers(CORS) with PHP headers), but couldn't get it to work as my $SERVER[ORIGIN] always returns null;

This is my https://dev.mycompany.com/test-cors.php file:

 <?

     header("Access-Control-Allow-Origin: https://www.mycompany.com");
     header("Access-Control-Allow-Methods: GET");
     header("Content-Type: application/json; charset=UTF-8");    
     $myObj->name = "John";
     $myObj->age = 30;
     $myObj->city = "New York";

     $myJSON = json_encode($myObj);

     echo $myJSON;

 ?>

I am trying to call the json.php with ajax from my https://dev.mycompany.com server to see if I would get JSON data back. I was expecting to get an error, but instead got the data retrieved alert message.

Here is my jquery call from the dev server on ajax.js.

     $.ajax({
            url: "test-cors.php",
            type: 'GET',
            dataType: 'json', // added data type
            success: function(data) {
                    alert('data retrieved');

            },
            error: function (jqXHR, textStatus, errorThrown) { 
                alert(textStatus);
            }
    
});
Moxie C
  • 442
  • 1
  • 15
  • 32
  • Your ajax request is made to the to the [same origin](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). CORS only works for cross origin. (Hence the name.) – Ivar Jul 31 '20 at 15:53

1 Answers1

0

The origin header is a header your browser sends to the server, indicating the origin (domain) of the request. In your case, test-core.php is on the same origin (dev.mycompany.com) as the Ajax call and thus allowed. The CORS headers are ignored. When performing this request from another origin (for ex. localhost) it would fail.

I only want certain domains to have access to my php file.

Please be aware that CORS headers are not a way to specify "access" some url/file. The Access-Control-Allow-Origin header limits browsers to perform requests to a certain url while on a certain location (for example, are you allowed to call an API on yoursite[.]com while the browser is on stackoverflow.com). It has nothing to do with actual access management.

n9iels
  • 867
  • 7
  • 21