Skip to content

Instantly share code, notes, and snippets.

@rchrd2
Created June 3, 2017 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rchrd2/c5886e6805d6232e4f378ae564ed7ab3 to your computer and use it in GitHub Desktop.
Save rchrd2/c5886e6805d6232e4f378ae564ed7ab3 to your computer and use it in GitHub Desktop.
Poor man's php cache. Saves to files. Includes expiry.
<?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