Note: If you are using PHP 5.1 or newer, you can save a system call by replacing time() with SERVER['REQUEST_TIME'].
<?php
// Caching using simple file swap cache. PHP4/PHP5
// Caching code by Rasmus Lerdorf
// February 1, 2006
// Note: If you are using PHP 5.1 or newer, you can save
// a system call by replacing time() with SERVER['REQUEST_TIME']
error_reporting(E_ALL);
// The ./ location puts the file in the root of your
// web server, usually
define('CACHEDIR', './');
$request = 'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&results=1';
// If you make different types of requests, you'll want to implement
// some sort of mapping from the request to unique filenames.
$cache_filename = 'ImageMad1';
$cache_fullpath = CACHEDIR . $cache_filename;
// Number of seconds until the cache gets stale
$cache_timeout = 7200;
// Check the cache
$response = request_cache($request, $cache_fullpath, $cache_timeout);
if ($response === false) {
die('Request failed');
}
// Output the XML
echo htmlspecialchars($response, ENT_QUOTES);
// This is the main caching routine. More robust error checking should
// be implemented.
function request_cache($url, $dest_file, $timeout = 7200) {
if (!file_exists($dest_file) || filemtime($dest_file) < (time() - $timeout)) {
$data = file_get_contents($url);
if ($data === false)
return false;
$tmpf = tempnam('/tmp', 'YWS');
$fp = fopen($tmpf, "w");
fwrite($fp, $data);
fclose($fp);
rename($tmpf, $dest_file);
} else {
return file_get_contents($dest_file);
}
return ($data);
}
?>