Click to See Complete Forum and Search --> : Page Caching
cwilkey
02-15-2007, 10:02 AM
All,
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.
<?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);
}
?>
NightShift58
02-15-2007, 12:11 PM
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.
cwilkey
02-15-2007, 12:34 PM
Any suggestions?
SlappyTheFish
02-16-2007, 10:43 AM
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.
cwilkey
02-16-2007, 10:56 AM
That would be much appreciated. Thank you!
bokeh
02-16-2007, 04:28 PM
I would have expanded the cache function Something like this?<?php
class Cache
{
/******************************************************
CLASSNAME:
Cache
AUTHOR:
bokeh
THREAD:
http://webdeveloper.com/forum/showthread.php?t=138529
PURPOSE:
To handle server-side and client-side caching of local
pages. It also GZips all output to save on bandwidth.
PERMISSIONS:
Be certain this script has sufficient permission
to read from and write to the cache directory.
EXAMPLE USE (your script):
<?php
# right at the start of your script
require_once('class.cache.php');
# now call the cache class,
# first argument: cache location,
# second argument: cache file duration in seconds.
$cache = new cache('./cache/', 3600);
?>
Your script content here!
<?php
# right at the end of your script
$cache->output();
?>
******************************************************/
var $buffer;
function Cache($location, $expires)
{
ob_start();
if(empty($_POST))
{
if((file_exists($this->filename = $location . md5($_SERVER['REQUEST_URI'])))
and (filemtime($this->filename) > (time() - $expires)))
{
$this->buffer = file_get_contents($this->filename);
$this->output(false);
}
}
}
function CachePage()
{
if(empty($_POST))
{
$fp = fopen($this->filename, 'w');
fwrite($fp, $this->buffer, strlen($this->buffer));
fclose($fp);
}
}
function output($cache = true)
{
$this->buffer or $this->buffer = ob_get_clean();
if($cache) $this->CachePage();
header('Etag: "'.($hash = md5($this->buffer)).'"');
if(isset($_SERVER['HTTP_IF_NONE_MATCH']))
{
if($hash == trim(stripslashes($_SERVER['HTTP_IF_NONE_MATCH']), '"'))
{
die(header("HTTP/1.1 304 Not Modified"));
}
}
die(ob_gzhandler($this->buffer, 1));
}
}
?>
NightShift58
02-16-2007, 06:59 PM
Perhaps not as professional, but yes, in that direction...
bokeh
02-18-2007, 04:31 AM
Perhaps not as professional, but yes, in that direction...What do you mean?
NightShift58
02-18-2007, 05:30 AM
Responding to your question: Something like this?
Yes, something like this - I wouldn't have done as professionally, but it would've have been in that general direction...
bokeh
02-18-2007, 05:38 AM
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
function CacheUriLocally($URI, $CachePath, $expires)
{
/*******************************************************
FUNCTION NAME:
CacheUriLocally
AUTHOR:
bokeh
THREAD:
http://webdeveloper.com/forum/showthread.php?t=138529
PURPOSE:
To cache a local copy of any URI.
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.
*********************************************************/
if((file_exists($filename = $CachePath . md5($URI)))
and (filemtime($filename) > (time() - $expires)))
{
return file_get_contents($filename);
}
$fp = fopen($filename, 'w');
fwrite($fp, $rtn = file_get_contents($URI));
fclose($fp);
return $rtn;
}
echo CacheUriLocally('http://www.google.com/', 'cache/', 3600);
?>
cwilkey
02-20-2007, 04:19 PM
Thank you all. This is perfect.