Skip to content

Instantly share code, notes, and snippets.

@klipitkas
Last active January 10, 2020 14:29
Show Gist options
  • Select an option

  • Save klipitkas/7131b574f59abc1aa2aff6e6a4fd74b5 to your computer and use it in GitHub Desktop.

Select an option

Save klipitkas/7131b574f59abc1aa2aff6e6a4fd74b5 to your computer and use it in GitHub Desktop.
Small cache implementation in PHP
<?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