-2
<?php
define('CACHE_PATH', $_SERVER["DOCUMENT_ROOT"]."/cachefiles/");
// how long to keep the cache files (hours)
define('CACHE_TIME', 12); 
// return location and name for cache file 
function cache_file() 
{ 
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}

// display cached file if present and not expired 
function cache_display() 
{ 
    $file = cache_file(); 
    // check that cache file exists and is not too old 
    if(!file_exists($file)) return; 
    if(filemtime($file) < time() - CACHE_TIME * 3600) return; 
    // if so, display cache file and stop processing
    readfile($file);
    exit; 
} 

// write to cache file 
function cache_page($content) 
{ 
    if(false !== ($f = @fopen(cache_file(), 'w'))) { 
        fwrite($f, $content);
        fclose($f); 
    } 
    return $content; 
} 

// execution stops here if valid cache file found
cache_display(); 

// enable output buffering and create cache file 
ob_start('cache_page');
?>

This code above creates cache with random name

e.g.

4c556ca729a88177e72946a4c3732f62

a87aef8e1d11cee944a8854ab8377ac6

85f2e557d6b483fc06db804d35e6580f

How can it make it stores cache pages with actual page name, like

home-4c556ca729a88177e72946a4c3732f62

about-a87aef8e1d11cee944a8854ab8377ac6

me-85f2e557d6b483fc06db804d35e6580f

Hiroshi Rana
  • 978
  • 2
  • 9
  • 18

1 Answers1

1

The OP's issue is found in the cache_file() method. This method handles the building of the name of the cached file when finding or making a new one.

$_SERVER['REQUEST_URI']

Will return the whole page and variables (ex. /index.php?var=1).

In cache_file(), it builds the name by taking an MD5 hash of the request and building the full path to the new file.

CACHE_PATH . md5($_SERVER['REQUEST_URI']);

The OP's request was to modify the request to show home/about/me in the cached file name. This can be done by parsing the URI for the name OR simply using the file's name. I will use no rewire http://domain.tld/index.php as an example.

basename(__FILE__, ".php"); //gives index on index.php

Using this, we then modify

CACHE_PATH .basename(__FILE__, ".php") . "-" . md5($_SERVER['REQUEST_URI']);

The following will give

../path/to/cache/index-{md5hash}
UnholyRanger
  • 1,977
  • 14
  • 24