<?php
Class Cache
{
Private $dir = "data/cache/";//define Cache directory
Private $key = ' c_a_sss '; FileName MD5 encryption key
function Set_dir ($dirpath)
{
$this->dir= $dirpath;
$this->make_dir ($this->dir);
}
function Read ($key, $minutes =1)
{
$filename = $this->get_filename ($key);
if ($datas = @file_get_contents ($filename))
{
$datas = Unserialize ($datas);
if (Time ()-$datas [' Time '] < $minutes *60)
{
return $datas [' data '];
}
}
return false;
}
function Write ($key, $data)
{
$filename = $this->get_filename ($key);
if ($handle = fopen ($filename, ' w+ '))
{
$datas = Array (' Data ' => $data, ' time ' =>time ());
Flock ($handle, LOCK_EX);
$rs = fputs ($handle, serialize ($datas));
Flock ($handle, lock_un);
Fclose ($handle);
if ($rs!==false) {return true; }
}
return false;
}
function Clear_all ()
{
$dir = $this->dir;
$this->del_file ($dir);
}
Private Function Get_filename ($key)
{
Return $this->dir. $key. ' _ '. MD5 ($key. $this->key);
}
Private Function Make_dir ($path)
{
if (! file_exists ($path))
{
$this->make_dir (dirname ($path));
if (! mkdir ($path, 0777))
Die (' Cannot create cache folder '. $path);
}
}
Private Function Del_file ($dir)
{
if (Is_dir ($dir))
{
$DH =opendir ($dir);//Open Directory//list all files in the directory and remove them. And..
while (false!== ($file = Readdir ($DH))) {
if ($file!= "." && $file!= "...") {
$fullpath = $dir. " /". $file;
if (!is_dir ($fullpath)) {
Unlink ($fullpath);
} else {
$this->del_file ($fullpath);
}
}
}
Closedir ($DH);
}
}
}
$cache = new cache ();
$cache->set_dir (' data/cache_dir/');
$data = $cache->read (' sys ', 1);
if (empty ($data))
{
$data =array (' AA ' =>1111, ' BB ' =>2222, ' Date ' =>date (' y-m-d h:i:s '));
$cache->write (' sys ', $data);
}
Print_r ($data);