Created
June 3, 2017 22:38
-
-
Save rchrd2/c5886e6805d6232e4f378ae564ed7ab3 to your computer and use it in GitHub Desktop.
Poor man's php cache. Saves to files. Includes expiry.
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 | |
function add_cache($key, $value, $ttl) { | |
$dir = __DIR__.'/../cache/'; | |
// Remove slashes for security | |
$filename = $dir . str_replace('/', '', $key); | |
// Store expiry in first line | |
$lines = [(string)(time() + (int)$ttl), $value ]; | |
if (!file_exists($dir)) mkdir($dir, 0755, true); | |
file_put_contents($filename, implode("\n", $lines)); | |
} | |
function get_cache($key) { | |
// Remove slashes for security | |
$filename = __DIR__.'/../cache/'.str_replace('/', '', $key); | |
if (file_exists($filename)) { | |
$contents = file_get_contents($filename); | |
$lines = explode("\n", $contents); | |
$expiry = array_shift($lines); | |
if (time() > (int)$expiry) { | |
unlink($filename); | |
} else { | |
return implode("\n", $lines); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment