Proxying HTTP requests with PHP

The following code will proxy requests to an external API.

This has several advantages:

  • Control over an API key
  • Set caching headers to prevent overuse of an API
  • Prevent issues with cross-domain scripting errors
  • Limit the scope of what APIs can be called through your proxy
$query = urlencode($_GET['query']);
$url = '';

$url = "http://blekko.com/ws/?q=%22" . $query . "%22+/json&auth=";
set_time_limit(30);

$s = fopen($url,"rb");

$seconds_to_cache = 3600 * 24;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");

foreach ($http_response_header as $h) {
        header($h);
}

header($h);

while (!feof($s)) {
        echo fread($s, 4096);
}

fclose($s);

Leave a Reply

Your email address will not be published. Required fields are marked *