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

codeigniter4 / CodeIgniter4 / 3755643596

pending completion
3755643596

push

github

GitHub
Merge pull request #7004 from kenjis/fix-db-session-tests

16207 of 18979 relevant lines covered (85.39%)

174.73 hits per line

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

0.0
/system/Session/Handlers/MemcachedHandler.php
1
<?php
2

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

12
namespace CodeIgniter\Session\Handlers;
13

14
use CodeIgniter\I18n\Time;
15
use CodeIgniter\Session\Exceptions\SessionException;
16
use Config\App as AppConfig;
17
use Memcached;
18
use ReturnTypeWillChange;
19

20
/**
21
 * Session handler using Memcache for persistence
22
 */
23
class MemcachedHandler extends BaseHandler
24
{
25
    /**
26
     * Memcached instance
27
     *
28
     * @var Memcached|null
29
     */
30
    protected $memcached;
31

32
    /**
33
     * Key prefix
34
     *
35
     * @var string
36
     */
37
    protected $keyPrefix = 'ci_session:';
38

39
    /**
40
     * Lock key
41
     *
42
     * @var string|null
43
     */
44
    protected $lockKey;
45

46
    /**
47
     * Number of seconds until the session ends.
48
     *
49
     * @var int
50
     */
51
    protected $sessionExpiration = 7200;
52

53
    /**
54
     * @throws SessionException
55
     */
56
    public function __construct(AppConfig $config, string $ipAddress)
57
    {
58
        parent::__construct($config, $ipAddress);
×
59

60
        if (empty($this->savePath)) {
×
61
            throw SessionException::forEmptySavepath();
×
62
        }
63

64
        // Add sessionCookieName for multiple session cookies.
65
        $this->keyPrefix .= $config->sessionCookieName . ':';
×
66

67
        if ($this->matchIP === true) {
×
68
            $this->keyPrefix .= $this->ipAddress . ':';
×
69
        }
70

71
        if (! empty($this->keyPrefix)) {
×
72
            ini_set('memcached.sess_prefix', $this->keyPrefix);
×
73
        }
74

75
        $this->sessionExpiration = $config->sessionExpiration;
×
76
    }
77

78
    /**
79
     * Re-initialize existing session, or creates a new one.
80
     *
81
     * @param string $path The path where to store/retrieve the session
82
     * @param string $name The session name
83
     */
84
    public function open($path, $name): bool
85
    {
86
        $this->memcached = new Memcached();
×
87
        $this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); // required for touch() usage
×
88

89
        $serverList = [];
×
90

91
        foreach ($this->memcached->getServerList() as $server) {
×
92
            $serverList[] = $server['host'] . ':' . $server['port'];
×
93
        }
94

95
        if (
96
            ! preg_match_all(
×
97
                '#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#',
×
98
                $this->savePath,
×
99
                $matches,
×
100
                PREG_SET_ORDER
×
101
            )
×
102
        ) {
103
            $this->memcached = null;
×
104
            $this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
×
105

106
            return false;
×
107
        }
108

109
        foreach ($matches as $match) {
×
110
            // If Memcached already has this server (or if the port is invalid), skip it
111
            if (in_array($match[1] . ':' . $match[2], $serverList, true)) {
×
112
                $this->logger->debug(
×
113
                    'Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]
×
114
                );
×
115

116
                continue;
×
117
            }
118

119
            if (! $this->memcached->addServer($match[1], (int) $match[2], $match[3] ?? 0)) {
×
120
                $this->logger->error(
×
121
                    'Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.'
×
122
                );
×
123
            } else {
124
                $serverList[] = $match[1] . ':' . $match[2];
×
125
            }
126
        }
127

128
        if (empty($serverList)) {
×
129
            $this->logger->error('Session: Memcached server pool is empty.');
×
130

131
            return false;
×
132
        }
133

134
        return true;
×
135
    }
136

137
    /**
138
     * Reads the session data from the session storage, and returns the results.
139
     *
140
     * @param string $id The session ID
141
     *
142
     * @return false|string Returns an encoded string of the read data.
143
     *                      If nothing was read, it must return false.
144
     */
145
    #[ReturnTypeWillChange]
146
    public function read($id)
147
    {
148
        if (isset($this->memcached) && $this->lockSession($id)) {
×
149
            if (! isset($this->sessionID)) {
×
150
                $this->sessionID = $id;
×
151
            }
152

153
            $data = (string) $this->memcached->get($this->keyPrefix . $id);
×
154

155
            $this->fingerprint = md5($data);
×
156

157
            return $data;
×
158
        }
159

160
        return '';
×
161
    }
162

163
    /**
164
     * Writes the session data to the session storage.
165
     *
166
     * @param string $id   The session ID
167
     * @param string $data The encoded session data
168
     */
169
    public function write($id, $data): bool
170
    {
171
        if (! isset($this->memcached)) {
×
172
            return false;
×
173
        }
174

175
        if ($this->sessionID !== $id) {
×
176
            if (! $this->releaseLock() || ! $this->lockSession($id)) {
×
177
                return false;
×
178
            }
179

180
            $this->fingerprint = md5('');
×
181
            $this->sessionID   = $id;
×
182
        }
183

184
        if (isset($this->lockKey)) {
×
185
            $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);
×
186

187
            if ($this->fingerprint !== ($fingerprint = md5($data))) {
×
188
                if ($this->memcached->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
×
189
                    $this->fingerprint = $fingerprint;
×
190

191
                    return true;
×
192
                }
193

194
                return false;
×
195
            }
196

197
            return $this->memcached->touch($this->keyPrefix . $id, $this->sessionExpiration);
×
198
        }
199

200
        return false;
×
201
    }
202

203
    /**
204
     * Closes the current session.
205
     */
206
    public function close(): bool
207
    {
208
        if (isset($this->memcached)) {
×
209
            if (isset($this->lockKey)) {
×
210
                $this->memcached->delete($this->lockKey);
×
211
            }
212

213
            if (! $this->memcached->quit()) {
×
214
                return false;
×
215
            }
216

217
            $this->memcached = null;
×
218

219
            return true;
×
220
        }
221

222
        return false;
×
223
    }
224

225
    /**
226
     * Destroys a session
227
     *
228
     * @param string $id The session ID being destroyed
229
     */
230
    public function destroy($id): bool
231
    {
232
        if (isset($this->memcached, $this->lockKey)) {
×
233
            $this->memcached->delete($this->keyPrefix . $id);
×
234

235
            return $this->destroyCookie();
×
236
        }
237

238
        return false;
×
239
    }
240

241
    /**
242
     * Cleans up expired sessions.
243
     *
244
     * @param int $max_lifetime Sessions that have not updated
245
     *                          for the last max_lifetime seconds will be removed.
246
     *
247
     * @return false|int Returns the number of deleted sessions on success, or false on failure.
248
     */
249
    #[ReturnTypeWillChange]
250
    public function gc($max_lifetime)
251
    {
252
        return 1;
×
253
    }
254

255
    /**
256
     * Acquires an emulated lock.
257
     *
258
     * @param string $sessionID Session ID
259
     */
260
    protected function lockSession(string $sessionID): bool
261
    {
262
        if (isset($this->lockKey)) {
×
263
            return $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);
×
264
        }
265

266
        $lockKey = $this->keyPrefix . $sessionID . ':lock';
×
267
        $attempt = 0;
×
268

269
        do {
270
            if ($this->memcached->get($lockKey)) {
×
271
                sleep(1);
×
272

273
                continue;
×
274
            }
275

276
            if (! $this->memcached->set($lockKey, Time::now()->getTimestamp(), 300)) {
×
277
                $this->logger->error(
×
278
                    'Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID
×
279
                );
×
280

281
                return false;
×
282
            }
283

284
            $this->lockKey = $lockKey;
×
285
            break;
×
286
        } while (++$attempt < 30);
×
287

288
        if ($attempt === 30) {
×
289
            $this->logger->error(
×
290
                'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.'
×
291
            );
×
292

293
            return false;
×
294
        }
295

296
        $this->lock = true;
×
297

298
        return true;
×
299
    }
300

301
    /**
302
     * Releases a previously acquired lock
303
     */
304
    protected function releaseLock(): bool
305
    {
306
        if (isset($this->memcached, $this->lockKey) && $this->lock) {
×
307
            if (
308
                ! $this->memcached->delete($this->lockKey)
×
309
                && $this->memcached->getResultCode() !== Memcached::RES_NOTFOUND
×
310
            ) {
311
                $this->logger->error(
×
312
                    'Session: Error while trying to free lock for ' . $this->lockKey
×
313
                );
×
314

315
                return false;
×
316
            }
317

318
            $this->lockKey = null;
×
319
            $this->lock    = false;
×
320
        }
321

322
        return true;
×
323
    }
324
}
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