• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 20640580500

01 Jan 2026 02:52PM UTC coverage: 85.498%. Remained the same
20640580500

push

github

web-flow
refactor: Session library (#9831)

10 of 12 new or added lines in 6 files covered. (83.33%)

1 existing line in 1 file now uncovered.

21808 of 25507 relevant lines covered (85.5%)

204.02 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.13
/system/Session/Handlers/DatabaseHandler.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Session\Handlers;
15

16
use CodeIgniter\Database\BaseBuilder;
17
use CodeIgniter\Database\BaseConnection;
18
use CodeIgniter\Session\Exceptions\SessionException;
19
use Config\Database;
20
use Config\Session as SessionConfig;
21
use ReturnTypeWillChange;
22

23
/**
24
 * Base database session handler.
25
 *
26
 * Do not use this class. Use database specific handler class.
27
 */
28
class DatabaseHandler extends BaseHandler
29
{
30
    /**
31
     * The database group to use for storage.
32
     *
33
     * @var string
34
     */
35
    protected $DBGroup;
36

37
    /**
38
     * The name of the table to store session info.
39
     *
40
     * @var string
41
     */
42
    protected $table;
43

44
    /**
45
     * The DB Connection instance.
46
     *
47
     * @var BaseConnection
48
     */
49
    protected $db;
50

51
    /**
52
     * The database type.
53
     *
54
     * @var string
55
     */
56
    protected $platform;
57

58
    /**
59
     * Row exists flag.
60
     *
61
     * @var bool
62
     */
63
    protected $rowExists = false;
64

65
    /**
66
     * ID prefix for multiple session cookies.
67
     */
68
    protected string $idPrefix;
69

70
    /**
71
     * @throws SessionException
72
     */
73
    public function __construct(SessionConfig $config, string $ipAddress)
74
    {
75
        parent::__construct($config, $ipAddress);
12✔
76

77
        $this->table = $this->savePath;
12✔
78

79
        if ($this->table === '') {
12✔
UNCOV
80
            throw SessionException::forMissingDatabaseTable();
×
81
        }
82

83
        // Store Session configurations
84
        $this->DBGroup = $config->DBGroup ?? config(Database::class)->defaultGroup;
12✔
85
        // Add session cookie name for multiple session cookies.
86
        $this->idPrefix = $config->cookieName . ':';
12✔
87
        $this->db       = Database::connect($this->DBGroup);
12✔
88
        $this->platform = $this->db->getPlatform();
12✔
89
    }
90

91
    /**
92
     * Re-initialize existing session, or creates a new one.
93
     *
94
     * @param string $path The path where to store/retrieve the session
95
     * @param string $name The session name
96
     */
97
    public function open($path, $name): bool
98
    {
99
        if ($this->db->connID === false) {
2✔
100
            $this->db->initialize();
×
101
        }
102

103
        return true;
2✔
104
    }
105

106
    /**
107
     * Reads the session data from the session storage, and returns the results.
108
     *
109
     * @param string $id The session ID
110
     *
111
     * @return false|string Returns an encoded string of the read data.
112
     *                      If nothing was read, it must return false.
113
     */
114
    #[ReturnTypeWillChange]
115
    public function read($id)
116
    {
117
        if ($this->lockSession($id) === false) {
4✔
118
            $this->fingerprint = md5('');
×
119

120
            return '';
×
121
        }
122

123
        if (! isset($this->sessionID)) {
4✔
124
            $this->sessionID = $id;
4✔
125
        }
126

127
        $builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
4✔
128

129
        if ($this->matchIP) {
4✔
130
            $builder = $builder->where('ip_address', $this->ipAddress);
×
131
        }
132

133
        $this->setSelect($builder);
4✔
134

135
        $result = $builder->get()->getRow();
4✔
136

137
        if ($result === null) {
4✔
138
            // PHP7 will reuse the same SessionHandler object after
139
            // ID regeneration, so we need to explicitly set this to
140
            // FALSE instead of relying on the default ...
141
            $this->rowExists   = false;
2✔
142
            $this->fingerprint = md5('');
2✔
143

144
            return '';
2✔
145
        }
146

147
        $result = is_bool($result) ? '' : $this->decodeData($result->data);
2✔
148

149
        $this->fingerprint = md5($result);
2✔
150
        $this->rowExists   = true;
2✔
151

152
        return $result;
2✔
153
    }
154

155
    /**
156
     * Sets SELECT clause.
157
     *
158
     * @return void
159
     */
160
    protected function setSelect(BaseBuilder $builder)
161
    {
162
        $builder->select('data');
2✔
163
    }
164

165
    /**
166
     * Decodes column data.
167
     *
168
     * @param string $data
169
     *
170
     * @return false|string
171
     */
172
    protected function decodeData($data)
173
    {
174
        return $data;
1✔
175
    }
176

177
    /**
178
     * Writes the session data to the session storage.
179
     *
180
     * @param string $id   The session ID.
181
     * @param string $data The encoded session data.
182
     */
183
    public function write($id, $data): bool
184
    {
185
        if ($this->lock === false) {
4✔
186
            return $this->fail();
×
187
        }
188

189
        if ($this->sessionID !== $id) {
4✔
190
            $this->rowExists = false;
2✔
191
            $this->sessionID = $id;
2✔
192
        }
193

194
        if ($this->rowExists === false) {
4✔
195
            $insertData = [
2✔
196
                'id'         => $this->idPrefix . $id,
2✔
197
                'ip_address' => $this->ipAddress,
2✔
198
                'data'       => $this->prepareData($data),
2✔
199
            ];
2✔
200

201
            if (! $this->db->table($this->table)->set('timestamp', 'now()', false)->insert($insertData)) {
2✔
202
                return $this->fail();
×
203
            }
204

205
            $this->fingerprint = md5($data);
2✔
206
            $this->rowExists   = true;
2✔
207

208
            return true;
2✔
209
        }
210

211
        $builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
2✔
212

213
        if ($this->matchIP) {
2✔
214
            $builder = $builder->where('ip_address', $this->ipAddress);
×
215
        }
216

217
        $updateData = [];
2✔
218

219
        if ($this->fingerprint !== md5($data)) {
2✔
220
            $updateData['data'] = $this->prepareData($data);
2✔
221
        }
222

223
        if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
2✔
224
            return $this->fail();
×
225
        }
226

227
        $this->fingerprint = md5($data);
2✔
228

229
        return true;
2✔
230
    }
231

232
    /**
233
     * Prepare data to insert/update.
234
     */
235
    protected function prepareData(string $data): string
236
    {
237
        return $data;
2✔
238
    }
239

240
    /**
241
     * Closes the current session.
242
     */
243
    public function close(): bool
244
    {
245
        return ($this->lock && ! $this->releaseLock()) ? $this->fail() : true;
×
246
    }
247

248
    /**
249
     * Destroys a session.
250
     *
251
     * @param string $id The session ID being destroyed.
252
     */
253
    public function destroy($id): bool
254
    {
255
        if ($this->lock) {
×
256
            $builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
×
257

258
            if ($this->matchIP) {
×
259
                $builder = $builder->where('ip_address', $this->ipAddress);
×
260
            }
261

262
            if (! $builder->delete()) {
×
263
                return $this->fail();
×
264
            }
265
        }
266

267
        if ($this->close()) {
×
268
            $this->destroyCookie();
×
269

270
            return true;
×
271
        }
272

273
        return $this->fail();
×
274
    }
275

276
    /**
277
     * Cleans up expired sessions.
278
     *
279
     * @param int $max_lifetime Sessions that have not updated
280
     *                          for the last max_lifetime seconds will be removed.
281
     *
282
     * @return false|int Returns the number of deleted sessions on success, or false on failure.
283
     */
284
    #[ReturnTypeWillChange]
285
    public function gc($max_lifetime)
286
    {
287
        return $this->db->table($this->table)->where(
1✔
288
            'timestamp <',
1✔
289
            "now() - INTERVAL {$max_lifetime} second",
1✔
290
            false,
1✔
291
        )->delete() ? 1 : $this->fail();
1✔
292
    }
293

294
    /**
295
     * Releases the lock, if any.
296
     */
297
    protected function releaseLock(): bool
298
    {
299
        if (! $this->lock) {
×
300
            return true;
×
301
        }
302

303
        // Unsupported DB? Let the parent handle the simple version.
304
        return parent::releaseLock();
×
305
    }
306
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc