Last active
January 10, 2020 14:29
-
-
Save klipitkas/7131b574f59abc1aa2aff6e6a4fd74b5 to your computer and use it in GitHub Desktop.
Small cache implementation in PHP
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 | |
| define('CACHE_TIME_DEFAULT', 10000); // in seconds. | |
| function cache_get($key) { | |
| $path = sys_get_temp_dir() . "/cache-$key"; | |
| if (!file_exists($path)) { | |
| return false; | |
| } | |
| $file = unserialize(file_get_contents($path)); | |
| if (time() - CACHE_TIME_DEFAULT >= filemtime($path)) { | |
| @unlink($path); | |
| } | |
| return $file; | |
| } | |
| function cache_set($key, $value) { | |
| $path = sys_get_temp_dir() . "/cache-$key"; | |
| if (file_put_contents($path, serialize($value), LOCK_EX) === false) { | |
| return false; | |
| } | |
| return true; | |
| } | |
| function cache_forget($key) { | |
| $path = sys_get_temp_dir() . "/cache-$key"; | |
| if (file_exists($path)) { | |
| unlink($path); | |
| return true; | |
| } | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment