Home > Code Snippets, PHP > File Caching Class

File Caching Class

June 26th, 2006

Howdy,

This comes useful when you think about getting content from other sites like RSS Feeds, text feeds, currency conversion rates etc. I tried to make this several times without such an enhancement. Finally the need arose and I have made this a reality.

I will need to find a better code highlighter plugin for wordpress before I can post many php codes and classes. Meanwhile this is being trying for a change:

class fileMgr
{
var $cache;
var $cacheTtl;

function fileMgr($cache = “cache”, $cacheTtl = 86400)
{
if(is_dir($cache))
$this->cache = $cache;
else
trigger_error(”Cache directory does not exist!”,1);

$this->cacheTtl = $cacheTtl;
}

function getFileContents($url)
{
$cacheFile = $this->cache . “/” . md5($url);
if(!$this->isAlive ($cacheFile))
$this->fetchFile($url, $cacheFile);

return file_get_contents ( $cacheFile );
}

function isAlive($cacheFile)
{
if(!file_exists($cacheFile)) return false;

$mtime = date(”U”, filemtime ( $cacheFile ));
$ctime = date(”U”);

if(($mtime + $this->cacheTtl) < $ctime) return false;
else return true;
}

function fetchFile ( $url, $cacheFile)
{
$tmp = file_get_contents( $url );
$fp = fopen ( $cacheFile, “w” );
fwrite ( $fp, $tmp );
fclose ( $fp );
}
}

  • Share/Bookmark

Code Snippets, PHP , ,

  1. No comments yet.
  1. No trackbacks yet.