forked from tharindud/conan-web
/
cache.php
executable file
·54 lines (46 loc) · 1.23 KB
/
cache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
// Copyright 2017, Tharindu Dissanayake <tharindud@gmail.com>.
// Published under the MIT license.
require_once("config.php");
// Convert a cache resource name to a cache file name.
function cache_filename($resource)
{
$file = $resource;
$bad = array("\"", "*", "/", ":", "=", "<", ">", "?", "\\", "|", " ", "@", ".", "-");
return CACHE_PATH.str_replace($bad, "_", $resource).".cache";
}
// Read a resource from the cache.
function cache_get($resource, $freshness = CACHE_DURATION)
{
$filename = cache_filename($resource);
$content = NULL;
if (file_exists($filename))
{
$now = new DateTime('now');
$mtime = new DateTime('@'.stat($filename)['mtime']);
if ($now > $mtime)
{
if ($now->getTimestamp() - $mtime->getTimestamp() < $freshness)
{
$file = fopen($filename, 'r');
$header = strlen($resource."\n\n");
if (trim(fread($file, $header)) == $resource)
{
$content = fread($file, filesize($filename) - $header);
}
fclose($file);
}
}
}
return $content;
}
// Write a resource to the cache.
function cache_put($resource, $content)
{
$filename = cache_filename($resource);
$file = fopen($filename, 'w');
fwrite($file, $resource."\n\n");
fwrite($file, $content);
fclose($file);
}
?>