Created
December 18, 2012 08:41
-
-
Save atree/4326198 to your computer and use it in GitHub Desktop.
PHP API proxy with caching build in.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// apiproxy [atree 12/18/2012] | |
// In order for the cache to work properly, | |
// there needs to be a folder under this script's folder | |
// named temp with the 777 permissions set. | |
// Don't fret if you don't have this, it will just continue on | |
// | |
// this cache will write to here every 12 hours (default) | |
// | |
// settings // | |
$cache_file = 'temp/api-cache.txt'; | |
$recreate_cache = false; | |
$show_cache = false; | |
$timestamp = time(); | |
$cached_hours = 12; | |
// if we have the cache, use it.. if it has expired set flag to recreate it // | |
if (file_exists($cache_file)) { | |
$show_cache = true; | |
$fh = fopen($cache_file, 'r'); | |
$cur_cache = fgets($fh); | |
if (($timestamp - $cur_cache) > (3600*$cached_hours) ) { // 3600 == 1 hour, default cache is 12 hours | |
$recreate_cache = true; | |
} | |
} else { | |
// we don't have one created // | |
$recreate_cache = true; | |
} | |
// if we should show, lets show // | |
if ($show_cache) { | |
$cache = fgets($fh); | |
header("Connection: close"); | |
header("Content-Length: " . mb_strlen($cache)); | |
echo trim($cache); | |
fclose($fh); | |
flush(); // flush to the browser [try to get response to browser before doing anything else] // | |
} | |
// if we need to create it, let's do that here // | |
if ($recreate_cache) { | |
$fh = fopen($cache_file, 'w'); | |
fwrite($fh, $timestamp ."\n"); | |
$base_url = "awesome-product-url-returning-json"; | |
$product_list = array(105,106,107,108,109,110,115,166,149,184); | |
$product_data = array(); | |
$brand_id = 100; | |
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'; | |
$api_data = "["; | |
foreach($product_list as $product_id => $pid) { | |
$ch = curl_init(); | |
$extended_url = $base_url . $pid . "/" . $brand_id . "/"; | |
curl_setopt($ch, CURLOPT_URL, $extended_url); | |
curl_setopt($ch, CURLOPT_USERAGENT, $agent); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
$json = curl_exec($ch); | |
$api_data = $api_data . $json; | |
if ($pid != end($product_list)) | |
$api_data = $api_data . ','; | |
} | |
$api_data = $api_data . ']'; | |
fwrite($fh, $api_data); | |
fclose($fh); | |
} | |
// if we didn't show (didn't have one) but created something, show what we created. [don't return empty] // | |
if (!$show_cache && $recreate_cache) { | |
echo $api_data; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment