This cache snippet works exactly as I want except the cache files are always being generated in the top level/main www directory. What I want to do is have the files generated in a separate folder i.e. /cache. Can anyone help modify it please?
<?php
define('CACHEDIR', './');
$request = 'http://someurl.com';
$cache_filename = CACHEDIR.md5($request);
$cache_fullpath = CACHEDIR.$cache_filename;
// Number of seconds until the cache gets stale and is replaced. 172800 = 48hrs
$cache_timeout = 100;
// 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.
function request_cache($request, $dest_file, $timeout=7200) {
if(!file_exists($dest_file) || filemtime($dest_file) < (time()-$timeout)) {
$data = file_get_contents($request);
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);
}
?>