Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Caching pages

need a little help



2:55 pm on Jan 11, 2007 (gmt 0)

10+ Year Member

Hi guys, I've spent all day trying to make this work but this is over my head. Basicly I want this code to cache my pages, store them in my cache directory fo 1h and display them if they are there.

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:

// 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);

return $content;

function get_url () {
if (!isset($_SERVER['REQUEST_URI'])) {
} else {
$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));

// 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'];

// Display cache (if any)

// Enable output buffering, with our caching callback
ob_start ('cache_page');


Many thanks for your help!


3:00 pm on Jan 11, 2007 (gmt 0)

10+ Year Member

I would say you probably need to change this line:

define ('cache_dir', './cache/');

Change ./cache/ to the full path and make sure its writable. I dont know.. This seems like a bit lengthy for caching..

[edited by: jatar_k at 3:02 pm (utc) on Jan. 11, 2007]
[edit reason] no urls thanks [/edit]


3:51 pm on Jan 11, 2007 (gmt 0)

10+ Year Member

Thank you for your reply. I have tried it each and everyway without much luck, thats why I'm posting it here.


9:20 pm on Jan 11, 2007 (gmt 0)

10+ Year Member

I got it, thanks. It was my path... sometimes you just need to walk away from your PS for a while.

Anyway, if you see anything wrong with this code, let me know. Thanks again.


Featured Threads

Hot Threads This Week

Hot Threads This Month