Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 91947fd30f
Fetching contributors…

Cannot retrieve contributors at this time

83 lines (69 sloc) 2.118 kb
<?php
class FileCache
{
static private $_instance = null;
static function getInstance()
{
if(FileCache::$_instance == null)
FileCache::$_instance = new FileCache();
return FileCache::$_instance;
}
function add($key,$data)
{
$filename = $this->getFileName($key);
if (file_exists($filename))
{
return false;
}
return $this->set($key,$data);
}
// This is the function you store information with
function set($key,$data)
{
// Opening the file
$h = fopen($this->getFileName($key),'w+'); //a+
if (!$h) return false;//throw new Exception('Could not write to cache');
// Serializing along with the TTL
$data = serialize(array(time(),$key,$data));
if (fwrite($h,$data)===false) //"$data\n"
{
return false;//throw new Exception('Could not write to cache');
}
fclose($h);
return true;
}
// General function to find the filename for a certain key
private function getFileName($key)
{
$key = $key.'.txt';
return dirname(dirname(__FILE__)).'/cache/' .$key;
}
// The function to fetch data returns false on failure
function get($key)
{
$filename = $this->getFileName($key);
if (!file_exists($filename) || !is_readable($filename)) return false;
$lines = file($filename);
// Loop through our array, show HTML source as HTML source; and line numbers too.
$data = array();
foreach ($lines as $line_num => $line)
{
$data[] = @unserialize($line);
}
if (!$data)
{
// Unlinking the file when unserializing failed
@unlink($filename);
return false;
}
return $data[0][2];
}
function delete($key)
{
$path = dirname(dirname(__FILE__)).'/cache/'.$key.'.txt';
if(file_exists($path))
return @unlink($path);
return false;
}
}
?>
Jump to Line
Something went wrong with that request. Please try again.