<?php
  
  // Our class
class FileCache {
/*
// constructing our cache engine
 $cache = new FileCache();

 function getUsers() {

    global $cache;

    // A somewhat unique key
    $key = 'getUsers:selectAll';

    // check if the data is not in the cache already
    if (!$data = $cache->fetch($key)) {
       // there was no cache version, we are fetching fresh data

       // assuming there is a database connection
       $result = mysql_query("SELECT * FROM users");
       $data = array();

       // fetching all the data and putting it in an array
       while($row = mysql_fetch_assoc($result)) { $data[] = $row; }

       // Storing the data in the cache for 10 minutes
       $cache->store($key,$data,600);
    }
    return $data;
}

$users = getUsers();
*/
	// General function to find the filename for a certain key
  private function getFileName($key) {

    return '/tmp/s_cache' . md5($key);
	//return ini_get('session.save_path') . '/s_cache' . md5($key);
  }
  
  // This is the function you store information with
  function store($key,$data,$ttl) {

    // Opening the file in read/write mode
    $h = fopen($this->getFileName($key),'a+');
    if (!$h) throw new Exception('Could not write to cache');

    flock($h,LOCK_EX); // exclusive lock, will get released when the file is closed

    fseek($h,0); // go to the beginning of the file

    // truncate the file
    ftruncate($h,0);

    // Serializing along with the TTL
    $data = serialize(array(time()+$ttl,$data));
    if (fwrite($h,$data)===false) {
      throw new Exception('Could not write to cache');
    }
    fclose($h);

  }

  function delete( $key ) {

        $filename = $this->getFileName($key);
        if (file_exists($filename)) {
            return unlink($filename);
        } else {
            return false;
        }

   }
	
  function fetch($key) {

      $filename = $this->getFileName($key);
      if (!file_exists($filename)) return false;
      $h = fopen($filename,'r');

      if (!$h) return false;

      // Getting a shared lock
      flock($h,LOCK_SH);

      $data = file_get_contents($filename);
      fclose($h);

      $data = @unserialize($data);
      if (!$data) {

         // If unserializing somehow didn't work out, we'll delete the file
         unlink($filename);
         return false;

      }

      if (time() > $data[0]) {

         // Unlinking when the file was expired
         unlink($filename);
         return false;

      }
      return $data[1];
   }
}
?>