file.php (1386B)
1 <?php 2 namespace Cache; 3 class File { 4 private $expire; 5 6 public function __construct($expire = 3600) { 7 $this->expire = $expire; 8 9 $files = glob(DIR_CACHE . 'cache.*'); 10 11 if ($files) { 12 foreach ($files as $file) { 13 $time = substr(strrchr($file, '.'), 1); 14 15 if ($time < time()) { 16 if (file_exists($file)) { 17 unlink($file); 18 } 19 } 20 } 21 } 22 } 23 24 public function get($key) { 25 $files = glob(DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*'); 26 27 if ($files) { 28 $handle = fopen($files[0], 'r'); 29 30 flock($handle, LOCK_SH); 31 32 $data = fread($handle, filesize($files[0])); 33 34 flock($handle, LOCK_UN); 35 36 fclose($handle); 37 38 return json_decode($data, true); 39 } 40 41 return false; 42 } 43 44 public function set($key, $value) { 45 $this->delete($key); 46 47 $file = DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.' . (time() + $this->expire); 48 49 $handle = fopen($file, 'w'); 50 51 flock($handle, LOCK_EX); 52 53 fwrite($handle, json_encode($value)); 54 55 fflush($handle); 56 57 flock($handle, LOCK_UN); 58 59 fclose($handle); 60 } 61 62 public function delete($key) { 63 $files = glob(DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*'); 64 65 if ($files) { 66 foreach ($files as $file) { 67 if (file_exists($file)) { 68 unlink($file); 69 } 70 } 71 } 72 } 73 }