CORS – cross origin request tutorial and example in PHP

CORS (cross origin resource sharing) can be used to make AJAX requests to different origins. Here are some points to note:
cors-request-header-response-header

  1. CORS un-aware browser will not make a CORS request.
  2. CORS aware browser will make CORS request with following header
    Origin: http://requestingdomain.com
    
  3. Server must respond with the following header for a cross origin request to be honoured by CORS aware browser.
    Access-Control-Allow-Origin: *
    ## or
    Access-Control-Allow-Origin: alloweddomain.com
    

    This way CORS unaware server don’t have to worry about CORS as they will never server this response header.

  4. Requests made from iframe will use parent domain/host for Origin header
  5. CORS is now supported in most modern browsers (Chrome, Forefox, IE11+).

CORS allow same domain example – request from same domain using jQuery

This is default case and everything works fine here. No extra request or reponse header due to CORS.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="result1">-</div>
<script type="text/javascript">
$.ajax({
  url: "/demo2/cors/hello_allowed_from_same.php"
})
.done(function( data ) {
  $("#result1").html(data);
});
</script>
refresh

CORS allow same domain example – request from different domain using jQuery

Here jQuery adds the following CORS header automatically:

Origin:http://infoheap.com

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="result1">-</div>
<script type="text/javascript">
$.ajax({
  url: "http://htmlsb.com/demo2/cors/hello_allowed_from_same.php"
})
.done(function( data ) {
  $("#result1").html(data);
});
</script>
refresh

Since server does not respond with right CORS header, Chrome throws this error in console:

XMLHttpRequest cannot load http://htmlsb.com/demo2/cors/hello_allowed_from_same.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://infoheap.com' is therefore not allowed access.

Note that here server actually served the request unaware of CORS. It was client Chrome which blocked it after getting response from server.

CORS allow any domain example – request from different domain using jQuery

Here following request header is added by jQuery

Origin:http://infoheap.com

And the following response header by server:

Access-Control-Allow-Origin: *

So everything works fine and result is displayed.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="result1">-</div>
<script type="text/javascript">
$.ajax({
  url: "http://htmlsb.com/demo2/cors/hello_allowed_from_any.php"
})
.done(function( data ) {
  $("#result1").html(data);
});
</script>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments