1+ <?php
2+ /**
3+ * FileAdapter.php
4+ *
5+ * This file is part of InitPHP Sessions.
6+ *
7+ * @author Muhammet ŞAFAK <info@muhammetsafak.com.tr>
8+ * @copyright Copyright © 2022 Muhammet ŞAFAK
9+ * @license ./LICENSE MIT
10+ * @version 2.0
11+ * @link https://www.muhammetsafak.com.tr
12+ */
13+
14+ namespace InitPHP \Sessions \Adapters ;
15+
16+ use InitPHP \Sessions \AbstractAdapter ;
17+ use InitPHP \Sessions \Interfaces \AdapterInterface ;
18+
19+ class FileAdapter extends AbstractAdapter implements AdapterInterface
20+ {
21+
22+ private $ path ;
23+
24+ private string $ prefix = 'sess_ ' ;
25+
26+ public function __construct (array $ options )
27+ {
28+ $ path = $ options ['path ' ];
29+ if (!is_dir ($ path ) || !is_writable ($ path )) {
30+ throw new \InvalidArgumentException ("Belirtilen dizin geçerli ve yazılabilir olmalıdır. " );
31+ }
32+ $ this ->path = $ path ;
33+ isset ($ options ['prefix ' ]) && $ this ->prefix = $ options ['prefix ' ];
34+ }
35+
36+
37+ public function read ($ id )
38+ {
39+ $ id = $ this ->prefix . $ id ;
40+
41+ return (string ) @file_get_contents ("{$ this ->path }/ $ id " );
42+ }
43+
44+ public function write ($ id , $ data )
45+ {
46+ $ id = $ this ->prefix . $ id ;
47+
48+ return file_put_contents ("{$ this ->path }/ $ id " , $ data ) !== false ;
49+ }
50+
51+ public function destroy ($ id )
52+ {
53+ $ id = $ this ->prefix . $ id ;
54+
55+ $ session = "{$ this ->path }/ $ id " ;
56+ if (file_exists ($ session )) {
57+ unlink ($ session );
58+ }
59+
60+ return true ;
61+ }
62+
63+ public function gc ($ max_lifetime )
64+ {
65+ $ files = glob ("{$ this ->path }/ {$ this ->prefix }* " );
66+ $ currentTime = time ();
67+
68+ foreach ($ files as $ file ) {
69+ if (filemtime ($ file ) + $ max_lifetime < $ currentTime && file_exists ($ file )) {
70+ unlink ($ file );
71+ }
72+ }
73+
74+ return true ;
75+ }
76+
77+ }
0 commit comments