-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileHandler.php
More file actions
109 lines (88 loc) · 2.44 KB
/
FileHandler.php
File metadata and controls
109 lines (88 loc) · 2.44 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
106
107
108
109
<?php
namespace Gt\Session;
use DirectoryIterator;
class FileHandler extends Handler {
const EMPTY_PHP_ARRAY = "a:0:{}";
protected string $path;
/** @var array<string, mixed> $cache */
protected array $cache;
/**
* @link http://php.net/manual/en/sessionhandlerinterface.open.php
* @param string $savePath The path where to store/retrieve the session.
* @param string $name The session name.
*/
public function open(string $savePath, string $name):bool {
$success = true;
$savePath = str_replace(
["/", "\\"],
DIRECTORY_SEPARATOR,
$savePath
);
$this->path = implode(DIRECTORY_SEPARATOR, [
$savePath,
$name,
]);
if(!is_dir($this->path)) {
$success = mkdir($this->path, 0775, true);
}
return $success;
}
/** @link http://php.net/manual/en/sessionhandlerinterface.close.php */
public function close():bool {
return true;
}
/** @link http://php.net/manual/en/sessionhandlerinterface.read.php */
public function read(string $sessionId):string {
if(isset($this->cache[$sessionId])) {
return $this->cache[$sessionId];
}
$filePath = $this->getFilePath($sessionId);
if(!file_exists($filePath)) {
return "";
}
$this->cache[$sessionId] = file_get_contents($filePath) ?: "";
return $this->cache[$sessionId];
}
/** @link http://php.net/manual/en/sessionhandlerinterface.write.php */
public function write(string $sessionId, string $sessionData):bool {
if($sessionData === self::EMPTY_PHP_ARRAY) {
return true;
}
$filePath = $this->getFilePath($sessionId);
$bytesWritten = file_put_contents($filePath, $sessionData);
return $bytesWritten !== false;
}
/** @link http://php.net/manual/en/sessionhandlerinterface.destroy.php */
public function destroy(string $id = ""):bool {
$filePath = $this->getFilePath($id);
if(file_exists($filePath)) {
return unlink($filePath);
}
return true;
}
/** @link http://php.net/manual/en/sessionhandlerinterface.gc.php */
public function gc(int $maxLifeTime):int|false {
$now = time();
$expired = $now - $maxLifeTime;
$num = 0;
foreach(new DirectoryIterator($this->path) as $fileInfo) {
if(!$fileInfo->isFile()) {
continue;
}
$lastModified = $fileInfo->getMTime();
if($lastModified < $expired) {
if(!unlink($fileInfo->getPathname())) {
return false;
}
$num++;
}
}
return $num;
}
protected function getFilePath(string $id):string {
return implode(DIRECTORY_SEPARATOR, [
$this->path,
$id,
]);
}
}