Data cache routine in PHP using CodeIgniter

This routine stores and reads temporary data to and from a file that can be used for minimizing database query.

 

# save object or array to a file.
function save_cache($username, $file, $data)
{
$this->load->helper('file');
if(!@mkdir("./data/profiles/".$username, 0777, false)) return false;
write_file('./data/profiles/'.$username.'/'.$file, base64_encode(serialize($data)));
return true;
}
# read file and return object or array value
function read_cache($username, $file)
{
$this->load->helper('file');
if(!($data = read_file('./data/profiles/'.$username.'/'.$file))) return false;
$data =  unserialize(base64_decode($data));
return $data;
}