Created
December 8, 2013 08:29
-
-
Save bg5sbk/7854636 to your computer and use it in GitHub Desktop.
A file system based cache class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class file_cache | |
{ | |
private $root_dir; | |
public function __construct($root_dir) { | |
$this->root_dir = $root_dir; | |
if (FALSE == file_exists($this->root_dir)) { | |
mkdir($this->root_dir, 0700, true); | |
} | |
} | |
public function set($key, $value) { | |
$key = $this->escape_key($key); | |
$file_name = $this->root_dir . '/' . $key; | |
$dir = dirname($file_name); | |
if (FALSE == file_exists($dir)) { | |
mkdir($dir, 0700, true); | |
} | |
file_put_contents($file_name, serialize($value), LOCK_EX); | |
} | |
public function get($key) { | |
$key = $this->escape_key($key); | |
$file_name = $this->root_dir . '/' . $key; | |
if (file_exists($file_name)) { | |
return unserialize(file_get_contents($file_name)); | |
} | |
return null; | |
} | |
public function remove($key) { | |
$key = $this->escape_key($key); | |
$file = $this->root_dir . '/' . $key; | |
if (file_exists($file)) { | |
unlink($file); | |
} | |
} | |
public function remove_by_search($key) { | |
$key = $this->escape_key($key); | |
$dir = $this->root_dir . '/' . $key; | |
if (strrpos($key, '/') < 0) | |
$key .= '/'; | |
if (file_exists($dir)) { | |
$this->remove_dir($dir); | |
} | |
} | |
private function escape_key($key) { | |
return str_replace('..', '', $key); | |
} | |
private function remove_dir($dirName) { | |
$result = false; | |
$handle = opendir($dirName); | |
while(($file = readdir($handle)) !== false) { | |
if($file != '.' && $file != '..') { | |
$dir = $dirName . DIRECTORY_SEPARATOR . $file; | |
is_dir($dir) ? $this->remove_dir($dir) : unlink($dir); | |
} | |
} | |
closedir($handle); | |
rmdir($dirName) ? true : false; | |
return $result; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example, cache in "/dev/shm":