PHP Proxy for Cross-Domain Requests That Works!

So I’ve been working on some AJAX stuff, dealing with Yahoo! Weather, specifically, and I realized I needed some way to make cross domain xmlhttprequests. Using a PHP Proxy seemed for me to be the easiest way to go, so I first tried what was suggested by Yahoo! I then tried some similar methods from others here and here, both to no avail. I then did some asking around on forums and made the necessary changes to make Yahoo’s example work. Just thought I’d share that with those of you who have similar troubles.

This is the PHP Proxy that I used. Note that:

  1. Your webserver’s PHP needs to support cURL
  2. This code doesn’t support POST requests, only GET.
<?php
// PHP Proxy example for Yahoo! Web services.
// Responds to both HTTP GET and POST requests
//
// Author: Jason Levitt
// December 7th, 2005
//(Modified by Suan-Aik Yeo)
$path = $_SERVER["QUERY_STRING"];
$url = $path;
// Open the Curl session
$session = curl_init($url);
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$xml = curl_exec($session);
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
echo $xml;
curl_close($session);
?>

When you’re using javascript to actually make the request, do something like this:

var proxy_name = "phpProxy.php";  //proxy's filename
var actualReq = "http://search.yahoo.com/blablabla?=...."; //actual request
var myDomain = "www.domainName.com/location/"; //where your proxy file is placed
var url = "http://"+myDomain+proxy_name+"/?"+actualReq;

//go on to do the usual httprequest steps...
httpRequest("GET",url,true,handleResponse);
...
...

Hope this helps!

Advertisements

One Response to “PHP Proxy for Cross-Domain Requests That Works!”

  1. Myspace Proxies Says:

    Myspace Proxies…

    The best proxies info may take a bit of effort to come upon….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: