Search code examples
javascriptphpsame-origin-policy

Why Same-Origin policy restricts access to Ajax but not to Php?


I'm working with this webservice it return an XML document.

When i call this webservice with Ajax i get:

XMLHttpRequest cannot load http://services.gisgraphy.com/geoloc/search?lat=36.81881&lng=10.16596&from=1&to=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.4:50000' is therefore not allowed access. 

When do the same thing with PHP:

<?php
    $xml = simplexml_load_file('http://services.gisgraphy.com/geoloc/search?lat=50.209298&lng=10.245&from=1&to=1');
    print_r($xml);
?>

Print it without getting restricted.

I just wonder the difference between those cases, and why it work for php file only ?

Cheers.


Solution

    • When you run PHP code, you do it on your own server. Nothing should restrict you from accessing other website because it's your server.

    • When you run Javascript Code, you usually run it on a client web browser. You don't own the client machine. And the client machine want to protect itself from connecting to malicious website.

    Imagine there's no same-origin policy :

    $.ajax({
      url: "http://somedrugdealingwebsite.com"
    })
    

    Client's IP will be registered as visitor of drug dealing website.