Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A (very) simple file based cache script. The class works great for my older pages on www.finalwebsites.com (all pages that are not served by WordPress)
<?php
class FileCache {
protected $cacheValidTime;
public $cacheIsValid = false;
protected $cacheFile;
function __construct($file, $valid = 86400) {
$this->setCacheFile($file);
$this->setCacheTime($valid);
if (!DEBUGTEST) {
if ($this->checkValidCache()) {
$this->cacheIsValid = true;
}
}
}
protected function setCacheFile($file) {
$this->cacheFile = CACHEDIR.$file.'.cache';
if (dirname($this->cacheFile) != CACHEDIR && !file_exists(dirname($this->cacheFile))) {
mkdir(dirname($this->cacheFile), 0755, true);
}
}
protected function setCacheTime($time) {
$this->cacheValidTime = $time;
}
protected function checkValidCache() {
$valid = false;
if (file_exists($this->cacheFile) && filesize($this->cacheFile) > 0) {
$timedif = (time() - filemtime($this->cacheFile));
if ($timedif < $this->cacheValidTime) {
$valid = true;
}
}
return $valid;
}
public function readCache() {
$handle = fopen($this->cacheFile, "r");
$contents = fread($handle, filesize($this->cacheFile));
fclose($handle);
return $contents;
}
public function writeCache($data) {
if ($data == '') return;
$fp = fopen($this->cacheFile, 'w');
if (flock($fp, LOCK_EX)) {
if (fwrite($fp, $data) === FALSE) {
$this->mailError('Can\'t write the cache file: '.$this->cacheFile);
}
flock($fp, LOCK_UN);
} else {
$this->mailError('Can\'t lock the cache file: '.$this->cacheFile);
}
fclose($fp);
}
protected function mailError($msg) {
//mail('your@email.com', 'Error in '.__CLASS__.' at '.date('Y-m-d'), $msg);
}
}
/* Example */
/*
$cache = new FileCache('yourPHPfile.php', 86400); // cache is valid for one day
if ($cache->cacheIsValid) {
echo $cache->readCache();
} else {
// Place here the PHP and HTML code
$data = 'abc';
$cache->writeCache($data);
echo $data;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment