A quick PHP Ajax proxy
My mashup uses Javascript to interact with the API. However directly calling the API using Javascript won't work. The browser intercepts and kills any AJAX requests to a remote hosts. So the solution? I wrote a simple proxy in PHP which sits between the Javascript and the Betavine API.
When a request is made the PHP will make the request to the API and return the response in the AJAX call. The Javascript on the web page then fooled into thinking that the AJAX response came from the same host as the web page.
It's a simple technique and is widely used for many mashups.
The code follows:
<?
ob_start();
function logf($message) {
$fd = fopen('proxy.log', "a");
fwrite($fd, $message . "\n");
fclose($fd);
}
?>
<?
$url = $_REQUEST;
logf($url);
$curl_handle = curl_init($url);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, "Owen's AJAX Proxy");
$content = curl_exec($curl_handle);
$content_type = curl_getinfo($curl_handle, CURLINFO_CONTENT_TYPE);
curl_close($curl_handle);
header("Content-Type: $content_type");
echo $content;
ob_flush();
?>
I'm using CURL to make the HTTP request. Notice that I set the User-Agent using
Have fun!
Owen.


Attribution