Search code examples
phpjavascriptajaxsame-origin-policy

To get around the ajax 'same origin policy', code for a PHP ajax request forwarder?


I want to bypass the ajax same-origin policy by having a php page on my site that basically acts like a JSON proxy. Eg i make an ajax request like this:

mysite.com/myproxy.php?url=blah.com/api.json&a=1&b=2

It then makes a request to:

blah.com/api.json?a=1&b=2

And returns the JSON (or whatever) result to the original requester. Now i assume i'd be stupidly reinventing the wheel if i wrote this php code (plus i don't know php!) - is there some pre-existing code to do this? I'm sure i'm not the only one who's butted my head up against the same-origin policy before.

Oh yeah JSONP isn't an option for this particular api.

Thanks all


Solution

  • Okay, here's something - Slap this into a php script, call it like this script.php?url=blah

    post the contents you want posted to the server.

    <?php
    
    
    $curlPost = http_build_query($_POST);
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $_GET['url']);
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    
    echo json_encode($data);
     ?>
    

    Now this script is a bit too open for my liking, so to increase security I would recommend that you add a list of domains to a white list.

    So add this to the top:

    $whitelist = array('http://www.google.com','http://www.ajax.com');
    $list = array();
    foreach($whitelist as $w)
     $list[] = parse_url($w,PHP_URL_HOST);
    
    $url = $_GET['url'];
    $url = pathinfo($url,PHP_URL_HOST);
    if(!in_array($url, $list)) die('no access to that domain');