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

codeigniter4 / CodeIgniter4 / 7293561159

21 Dec 2023 09:55PM UTC coverage: 85.237% (+0.004%) from 85.233%
7293561159

push

github

web-flow
Merge pull request #8355 from paulbalandan/replace

Add `replace` to composer.json

18597 of 21818 relevant lines covered (85.24%)

199.84 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\Session as SessionConfig;
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(SessionConfig $config, string $ipAddress)
57
    {
58
        parent::__construct($config, $ipAddress);
×
59

60
        $this->sessionExpiration = $config->expiration;
×
61

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

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

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

73
        ini_set('memcached.sess_prefix', $this->keyPrefix);
×
74
    }
75

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

87
        $serverList = [];
×
88

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

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

104
            return false;
×
105
        }
106

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

114
                continue;
×
115
            }
116

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

126
        if ($serverList === []) {
×
127
            $this->logger->error('Session: Memcached server pool is empty.');
×
128

129
            return false;
×
130
        }
131

132
        return true;
×
133
    }
134

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

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

153
            $this->fingerprint = md5($data);
×
154

155
            return $data;
×
156
        }
157

158
        return '';
×
159
    }
160

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

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

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

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

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

189
                    return true;
×
190
                }
191

192
                return false;
×
193
            }
194

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

198
        return false;
×
199
    }
200

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

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

215
            $this->memcached = null;
×
216

217
            return true;
×
218
        }
219

220
        return false;
×
221
    }
222

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

233
            return $this->destroyCookie();
×
234
        }
235

236
        return false;
×
237
    }
238

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

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

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

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

271
                continue;
×
272
            }
273

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

279
                return false;
×
280
            }
281

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

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

291
            return false;
×
292
        }
293

294
        $this->lock = true;
×
295

296
        return true;
×
297
    }
298

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

313
                return false;
×
314
            }
315

316
            $this->lockKey = null;
×
317
            $this->lock    = false;
×
318
        }
319

320
        return true;
×
321
    }
322
}
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