hpdl
|
1
|
1
|
<?php
|
|
2
|
/*
|
hpdl
|
153
|
3
|
$Id: cache.php 153 2005-08-04 12:57:59Z hpdl $
|
hpdl
|
1
|
4
|
|
|
5
|
osCommerce, Open Source E-Commerce Solutions
|
|
6
|
http://www.oscommerce.com
|
|
7
|
|
|
8
|
Copyright (c) 2004 osCommerce
|
|
9
|
|
|
10
|
Released under the GNU General Public License
|
|
11
|
|
|
12
|
Class usage examples:
|
|
13
|
|
|
14
|
- Caching HTML:
|
|
15
|
if ($osC_Cache->read('key', 60) === false) {
|
|
16
|
$osC_Cache->startBuffer();
|
|
17
|
------ PHP/HTML LOGIC HERE ------
|
|
18
|
$osC_Cache->stopBuffer();
|
|
19
|
}
|
|
20
|
|
|
21
|
echo $osC_Cache->getCache();
|
|
22
|
|
|
23
|
- Caching data (in memory):
|
|
24
|
if ($osC_Cache->read('key', 60) {
|
|
25
|
$variable = $osC_Cache->getCache();
|
|
26
|
} else {
|
|
27
|
$variable = array('some', 'data');
|
|
28
|
|
|
29
|
$osC_Cache->writeBuffer($variable);
|
|
30
|
}
|
|
31
|
*/
|
|
32
|
|
|
33
|
class osC_Cache {
|
|
34
|
var $cached_data,
|
|
35
|
$cache_key;
|
|
36
|
|
|
37
|
function write($key, &$data) {
|
|
38
|
$filename = DIR_FS_WORK . $key . '.cache';
|
|
39
|
|
|
40
|
if ($fp = @fopen($filename, 'w')) {
|
|
41
|
flock($fp, 2); // LOCK_EX
|
|
42
|
fputs($fp, serialize($data));
|
|
43
|
flock($fp, 3); // LOCK_UN
|
|
44
|
fclose($fp);
|
|
45
|
|
|
46
|
return true;
|
|
47
|
}
|
|
48
|
|
|
49
|
return false;
|
|
50
|
}
|
|
51
|
|
|
52
|
function read($key, $expire = 0) {
|
|
53
|
$this->cache_key = $key;
|
|
54
|
|
|
55
|
$filename = DIR_FS_WORK . $key . '.cache';
|
|
56
|
|
|
57
|
if (file_exists($filename)) {
|
|
58
|
$difference = floor((time() - filemtime($filename)) / 60);
|
|
59
|
|
|
60
|
if ( ($expire == '0') || ($difference < $expire) ) {
|
|
61
|
if ($fp = @fopen($filename, 'r')) {
|
|
62
|
$this->cached_data = unserialize(fread($fp, filesize($filename)));
|
|
63
|
|
|
64
|
fclose($fp);
|
|
65
|
|
|
66
|
return true;
|
|
67
|
}
|
|
68
|
}
|
|
69
|
}
|
|
70
|
|
|
71
|
return false;
|
|
72
|
}
|
|
73
|
|
|
74
|
function &getCache() {
|
|
75
|
return $this->cached_data;
|
|
76
|
}
|
|
77
|
|
|
78
|
function startBuffer() {
|
|
79
|
ob_start();
|
|
80
|
}
|
|
81
|
|
|
82
|
function stopBuffer() {
|
|
83
|
$this->cached_data = ob_get_contents();
|
|
84
|
|
|
85
|
ob_end_clean();
|
|
86
|
|
|
87
|
$this->write($this->cache_key, $this->cached_data);
|
|
88
|
}
|
|
89
|
|
|
90
|
function writeBuffer(&$data) {
|
|
91
|
$this->cached_data = $data;
|
|
92
|
|
|
93
|
$this->write($this->cache_key, $this->cached_data);
|
|
94
|
}
|
|
95
|
|
|
96
|
function clear($key) {
|
|
97
|
$key_length = strlen($key);
|
|
98
|
|
|
99
|
$d = dir(DIR_FS_WORK);
|
|
100
|
|
|
101
|
while ($entry = $d->read()) {
|
|
102
|
if ((strlen($entry) >= $key_length) && (substr($entry, 0, $key_length) == $key)) {
|
|
103
|
@unlink(DIR_FS_WORK . $entry);
|
|
104
|
}
|
|
105
|
}
|
|
106
|
|
|
107
|
$d->close();
|
|
108
|
}
|
|
109
|
}
|
|
110
|
?>
|