PHP cache to disk using fwrite

46 views Asked by At

I'm using the following codes to cache URLs visited, hopefully saving some CPU. At the beginning of the php files:

$url = $_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cache/cached-'.$file.'.html';
$cachetime = 900;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
  //  echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    readfile($cachefile);
    exit;
}
ob_start();

At the end of the php files:

// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser

This works fine, but it creates files using the full URI (ie including queries, # etc). I am trying to have the cached file written once, without anything else.

In other words, when someone visits mysite.com/index.php, I want one file index.php.html created. The if someone else visits mysite.com/index.php?sdgd=3534&#whatever&other&stuff I want the cached file to still be index.php.html therefore overwriting the previous index.php.html created. I do not want a cached file named index.php?sdgd=3534&#whatever&other&stuff.html - which seems to happen now.

I know it probably has to do with:

$cachefile = 'cache/cached-'.$file.'.html';

but couldn't figure it out myself.

How to accomplish this?

1

There are 1 answers

2
Johnny Bravo On

Thanks for the suggestions guys. That wasn't the case, so I'm gonna asnwer my own question. Apparently the answer was as easy as changing

$url = $_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"];

into

$url = strtok($_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"], '?');

This seems to cache a file with a name excluding the queries.