Forum Moderators: coopster
The problem I'm having is that I can't seem to store the cached files in the right spot, for some reason it saves them in my apache folder? I'm playing with this on my local machine. Here is my code:
<?php
// Define cache directory - change to your own directory
define ('cache_dir', './cache/');echo $cachedir;
// How long is data in cache valid - in hours
define ('cache_time', 24);
function cache_page ($content) {
// Get current URL
$url = get_url();
// Create a unique filename out of our URL
$filename = md5($url) . '.cache';
// Create data string
$data = time() . '¦' . $content;
// Write file
$f = fopen(cache_dir . $filename, 'w');
fwrite($f, $data);
fclose($f);
return $content;
}
function get_url () {
if (!isset($_SERVER['REQUEST_URI'])) {
$url = $_SERVER['REQUEST_URI'];
} else {
$url = $_SERVER['SCRIPT_NAME'];
$url = (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER['QUERY_STRING'] : '';
}
return $url;
}
function display_cache () {
// Get current URL
$url = get_url();
// Get filename of the current URL
$filename = md5($url) . '.cache';
$file = cache_dir . $filename;
// Cache exists?
if (!file_exists($file)) {
// No cache, exit function
return false;
}
// Get data
$f = fopen($file, 'r');
$data = fread($f, filesize($file));
fclose($f);
// Split timestamp and content
$data = explode('¦', $data, 2);
// Is data valid?
if (count($data)!= 2 OR!is_numeric($data['0'])) {
return false;
}
// Check if cache isn't too old
// If current time - cachetime is bigger than cached data
// Then not valid
if (time()-(cache_time*60*60) > $data['0']) {
return false;
}
// Cache is valid, display it, and end page
echo $data['1'];
die();
}
// Display cache (if any)
display_cache();
// Enable output buffering, with our caching callback
ob_start ('cache_page');
?>
Many thanks for your help!