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

codeigniter4 / CodeIgniter4 / 12518821104

27 Dec 2024 05:21PM UTC coverage: 84.426% (+0.02%) from 84.404%
12518821104

Pull #9339

github

web-flow
Merge 5caee6ae0 into 6cbbf601b
Pull Request #9339: refactor: enable instanceof and strictBooleans rector set

55 of 60 new or added lines in 34 files covered. (91.67%)

19 existing lines in 3 files now uncovered.

20437 of 24207 relevant lines covered (84.43%)

189.66 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
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\I18n\Time;
17
use CodeIgniter\Session\Exceptions\SessionException;
18
use Config\Session as SessionConfig;
19
use Memcached;
20
use ReturnTypeWillChange;
21

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

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

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

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

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

62
        $this->sessionExpiration = $config->expiration;
×
63

64
        if (empty($this->savePath)) {
×
65
            throw SessionException::forEmptySavepath();
×
66
        }
67

68
        // Add sessionCookieName for multiple session cookies.
69
        $this->keyPrefix .= $config->cookieName . ':';
×
70

71
        if ($this->matchIP === true) {
×
72
            $this->keyPrefix .= $this->ipAddress . ':';
×
73
        }
74

75
        ini_set('memcached.sess_prefix', $this->keyPrefix);
×
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 (
NEW
96
            in_array(preg_match_all(
×
97
                '#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#',
×
98
                $this->savePath,
×
99
                $matches,
×
100
                PREG_SET_ORDER
×
NEW
101
            ), [0, false], true)
×
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 ($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

© 2025 Coveralls, Inc