forked from phpgt/Session
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.php
More file actions
116 lines (95 loc) · 2.37 KB
/
Copy pathFileHandler.php
File metadata and controls
116 lines (95 loc) · 2.37 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
110
111
112
113
114
115
116
<?php
namespace Gt\Session;
use DirectoryIterator;
class FileHandler extends Handler {
protected $path;
protected $cache;
/**
* @link http://php.net/manual/en/sessionhandlerinterface.open.php
* @param string $save_path The path where to store/retrieve the session.
* @param string $name The session name.
*/
public function open($save_path, $name):bool {
$success = true;
$save_path = str_replace(
["/", "\\"],
DIRECTORY_SEPARATOR,
$save_path
);
$this->path = implode(DIRECTORY_SEPARATOR, [
$save_path,
$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
* @param string $session_id
*/
public function read($session_id):string {
if(isset($this->cache[$session_id])) {
return $this->cache[$session_id];
}
$filePath = $this->getFilePath($session_id);
if(!file_exists($filePath)) {
return "";
}
$this->cache[$session_id] = file_get_contents($filePath);
return $this->cache[$session_id];
}
/**
* @link http://php.net/manual/en/sessionhandlerinterface.write.php
* @param string $session_id
* @param string $session_data
*/
public function write($session_id, $session_data):bool {
$filePath = $this->getFilePath($session_id);
return file_put_contents($filePath, $session_data) > 0;
}
/**
* @link http://php.net/manual/en/sessionhandlerinterface.destroy.php
* @param string $session_id
*/
public function destroy($session_id):bool {
$filePath = $this->getFilePath($session_id);
if(file_exists($filePath)) {
return unlink($filePath);
}
return true;
}
/**
* @link http://php.net/manual/en/sessionhandlerinterface.gc.php
* @param int $maxlifetime
*/
public function gc($maxlifetime):bool {
$now = time();
$expired = $now - $maxlifetime;
foreach(new DirectoryIterator($this->path) as $fileInfo) {
if(!$fileInfo->isFile()) {
continue;
}
$lastModified = $fileInfo->getMTime();
if($lastModified < $expired) {
if(!unlink($fileInfo->getPathname())) {
return false;
}
}
}
return true;
}
protected function getFilePath(string $id):string {
return implode(DIRECTORY_SEPARATOR, [
$this->path,
$id,
]);
}
}