-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJG_Cache.php
More file actions
105 lines (83 loc) · 1.91 KB
/
Copy pathJG_Cache.php
File metadata and controls
105 lines (83 loc) · 1.91 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/*
For explanation and usage, see:
http://www.jongales.com/blog/2009/02/18/simple-file-based-php-cache-class/
*/
class JG_Cache {
function __construct($dir)
{
$this->dir = $dir;
}
private function _name($key)
{
return sprintf("%s/%s", $this->dir, sha1($key));
}
public function get($key, $expiration = 3600)
{
if ( !is_dir($this->dir) OR !is_writable($this->dir))
{
return FALSE;
}
$cache_path = $this->_name($key);
if (!@file_exists($cache_path))
{
return FALSE;
}
if (filemtime($cache_path) < (time() - $expiration))
{
$this->clear($key);
return FALSE;
}
if (!$fp = @fopen($cache_path, 'rb'))
{
return FALSE;
}
flock($fp, LOCK_SH);
$cache = '';
if (filesize($cache_path) > 0)
{
$cache = unserialize(fread($fp, filesize($cache_path)));
}
else
{
$cache = NULL;
}
flock($fp, LOCK_UN);
fclose($fp);
return $cache;
}
public function set($key, $data)
{
if ( !is_dir($this->dir) OR !is_writable($this->dir))
{
return FALSE;
}
$cache_path = $this->_name($key);
if ( ! $fp = fopen($cache_path, 'wb'))
{
return FALSE;
}
if (flock($fp, LOCK_EX))
{
fwrite($fp, serialize($data));
flock($fp, LOCK_UN);
}
else
{
return FALSE;
}
fclose($fp);
@chmod($cache_path, 0777);
return TRUE;
}
public function clear($key)
{
$cache_path = $this->_name($key);
if (file_exists($cache_path))
{
unlink($cache_path);
return TRUE;
}
return FALSE;
}
}