"; } return false; } $cache = file_get_contents(cacheFile); $cache = unserialize($cache); if (!is_array($cache)) { if (debug) { echo "cache is no array: " . __FILE__ . ":". __LINE__ . " \n
"; } resetCache(); return false; } if (!validateCache($cache)) { if (debug) { echo "invalid cache: " . __FILE__ . ":". __LINE__ . " \n
"; } resetCache(); return false; } $data = $cache['data']; if (!array_key_exists($dataKey, $data)) { if (debug) { echo "array key not found: " . __FILE__ . ":". __LINE__ . " \n
"; } 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
"; } 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
"; } return false; } $timestamp = $meta['timestamp']; if (debug) { var_dump([$timestamp, time(), (time() - cacheMaxAge), (time() - cacheMaxAge) > $timestamp]); } if ((time() - cacheMaxAge) > $timestamp) { if (debug) { echo "cache expired: " . __FILE__ . ":". __LINE__ . " \n
"; } return false; } if (!is_null($data) && $cache['data'] !== $data) { if (debug) { echo "data doesn't math: " . __FILE__ . ":". __LINE__ . " \n
"; } return false; } return true; }