I'm writing a script to do page caching. I've got the following code - which works, but I was wondering if anyone hand any input to make it run more efficiently.
Code:
<?php
error_reporting(E_ALL);
// The ./ location puts the file in the root of your
define('CACHEDIR', './');
// URL of page you wish to cache
$request = 'http://www.google.com';
$cache_filename = 'cached.php';
$cache_fullpath = CACHEDIR.$cache_filename;
// Number of seconds until the cache gets stale
$cache_timeout = 0;
// 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($url, $dest_file) {
$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);
return($data);
}
?>
I would have expanded the cache function to automatically (1) deliver the cached page if not stale or (2) deliver a fresh version if the cache is stale or (3) a fresh version if no cached copy is present.
I think your current version will also cause you grief retrieving he correct cached copy when requested. You need to devise a working system for naming the cached files.
I've just finished a caching class which will cache the output of any function and covers the points made by NightShift. It's not online yet, but if you can hold on a few days then I'll send you the link and you'd be welcome to use it.
Ok, the class above was for caching internal files and I didn't read the question properly. Now I have read it here is a function to cache external URIs locally.
PHP Code:
<?php
function CacheUriLocally($URI, $CachePath, $expires)
{
/*******************************************************
DESCRIPTION:
string CacheUriLocally( string URI, string CachePath, int expires )
INPUTS:
$URI is the full URI of the remote resource including
the scheme. $CachePath is an absolute or relative path
to the cache folder and must include a trailing slash.
$expires is the max age in seconds before the cached
data is considered stale.
RETURN VALUE:
Returns the URI output in a string
NOTES:
1) If you're opening a URI with special characters, such
as spaces, you need to encode the URI with urlencode().
2) Be certain this script has sufficient permission to
read from and write to the cache directory.
Bookmarks