Newer
Older
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
// ---------------------------------------------------------
// Global definition for the cache
// ---------------------------------------------------------
define('cacheFile', '.cache'); // File where the cache is being stored
define('cacheMaxAge', 300); // Time in s how long to hold the cache until reset
define('cacheHashAlgo', 'sha512'); // Hash algo to use for cache validation - http://de2.php.net/manual/de/function.hash.php#104987
// ---------------------------------------------------------
function getCache($dataKey = '') {
if (!file_exists(cacheFile)) {
if (debug) {
echo "cache file not found: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return false;
}
$cache = file_get_contents(cacheFile);
$cache = unserialize($cache);
if (!is_array($cache)) {
if (debug) {
echo "cache is no array: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
resetCache();
return false;
}
if (!validateCache($cache)) {
if (debug) {
echo "invalid cache: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
resetCache();
return false;
}
$data = $cache['data'];
if (!array_key_exists($dataKey, $data)) {
if (debug) {
echo "array key not found: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return false;
}
if (!empty($dataKey)) {
return $data[$dataKey];
}
return $data;
}
function writeCache($data) {
$hash = serialize($data);
$hash = hash('sha512', $hash);
$meta = [
'timestamp' => time(),
'hash' => $hash,
];
$cache = [
'meta' => $meta,
'data' => $data
];
$cacheSerialized = serialize($cache);
file_put_contents(cacheFile, $cacheSerialized);
if (validateCache($cache, $data)) {
if (debug) {
echo "valid cache: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return true;
}
resetCache();
return false;
}
function resetCache() {
if (file_exists(cacheFile)) {
return unlink(cacheFile);
} else {
return true;
}
}
function validateCache($cache, $data = null) {
$meta = $cache['meta'];
$data = $cache['data'];
$hashMeta = $meta['hash'];
$dataHash = serialize($data);
$dataHash = hash(cacheHashAlgo, $dataHash);
if (debug) {
var_dump([$hashMeta, $dataHash, $hashMeta !== $dataHash]);
}
if ($hashMeta !== $dataHash) {
if (debug) {
echo "hashes don't match: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return false;
}
$timestamp = $meta['timestamp'];
if ((time() - cacheMaxAge) > $timestamp) {
if (debug) {
echo "cache expired: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return false;
}
if (!is_null($data) && $cache['data'] !== $data) {
if (debug) {
echo "data doesn't math: " . __FILE__ . ":". __LINE__ . " \n<br>";
}
return false;
}
return true;
}