Skip to content

[HttpFoundation] Add native handlers for Memcache and Redis #48588

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: 7.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Run php-cs-fixer to follow coding standards
  • Loading branch information
mevdschee committed Dec 11, 2022
commit 015f4955ce28a897d78f7a98228802e9bedb3e6b
Original file line number Diff line number Diff line change
Expand Up @@ -25,58 +25,58 @@ class NativeMemcachedSessionHandler extends \SessionHandler
*/
public function __construct(string $savePath = null, array $sessionOptions = null)
{
//
//
// Sessions support (from: https://www.php.net/manual/en/memcached.sessions.php)
//
// Memcached provides a custom session handler that can be used to store user sessions in memcache.
// A completely separate memcached instance is used for that internally, so you can use a different
// server pool if necessary. The session keys are stored under the prefix memc.sess.key., so be aware
// Memcached provides a custom session handler that can be used to store user sessions in memcache.
// A completely separate memcached instance is used for that internally, so you can use a different
// server pool if necessary. The session keys are stored under the prefix memc.sess.key., so be aware
// of this if you use the same server pool for sessions and generic caching.
//
// - session.save_handler string
// Set to memcached to enable sessions support.
//
// - session.save_path string
// Defines a comma separated of hostname:port entries to use for session server
// Defines a comma separated of hostname:port entries to use for session server
// pool, for example "sess1:11211, sess2:11211".
//

$savePath ??= ini_get('session.save_path');
$savePath ??= \ini_get('session.save_path');

ini_set('session.save_path', $savePath);
ini_set('session.save_handler', 'memcached');

//
// Runtime Configuration (from: https://www.php.net/manual/en/memcached.configuration.php)
//
//
// Here's a short explanation of the configuration directives.
//
//
// - memcached.sess_locking bool
// Use session locking. Valid values: On, Off, the default is On.
//
//
// - memcached.sess_prefix string
// Memcached session key prefix. Valid values are strings less than 219 bytes long.
// Memcached session key prefix. Valid values are strings less than 219 bytes long.
// The default value is "memc.sess.key."
//
//
// - memcached.sess_lock_expire int
// The time, in seconds, before a lock should release itself. Setting to 0 results in the
// The time, in seconds, before a lock should release itself. Setting to 0 results in the
// default behaviour, which is to use PHP's max_execution_time. Default is 0.
//
//
// - memcached.sess_lock_retries int
// The number of times to retry locking the session lock, not including the first attempt.
// The number of times to retry locking the session lock, not including the first attempt.
// Default is 5.
//
//
// - memcached.sess_lock_wait_min int
// The minimum time, in milliseconds, to wait between session lock attempts. This value is
// double on each lock retry until memcached.sess_lock_wait_max is reached, after which any
// The minimum time, in milliseconds, to wait between session lock attempts. This value is
// double on each lock retry until memcached.sess_lock_wait_max is reached, after which any
// further retries will take sess_lock_wait_max seconds. The default is 150.
//

$sessionName = $sessionOptions['name'] ?? ini_get('session.name');
$sessionName = $sessionOptions['name'] ?? \ini_get('session.name');

$prefix = "memc.sess.key.$sessionName.";
$lock_expire = ini_get("max_execution_time") ?: 30; // 30s
$lock_wait_time = ini_get('memcached.sess_lock_wait_min') ?: 150; // 150ms
$lock_expire = \ini_get('max_execution_time') ?: 30; // 30s
$lock_wait_time = \ini_get('memcached.sess_lock_wait_min') ?: 150; // 150ms
$lock_retries = (int) ($lock_expire / ($lock_wait_time / 1000)); // 200x

ini_set('memcached.sess_locking', 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class NativeRedisSessionHandler extends \SessionHandler
*/
public function __construct(string $savePath = null, array $sessionOptions = null)
{
//
//
// PHP Session handler (from: https://github.com/phpredis/phpredis#php-session-handler)
//
// phpredis can be used to store PHP sessions. To do this, configure session.save_handler and session.save_path
Expand All @@ -34,31 +34,31 @@ public function __construct(string $savePath = null, array $sessionOptions = nul
// session.save_handler = redis
// session.save_path = "tcp://host1:6379?weight=1, tcp://host2:6379?weight=2&timeout=2.5, tcp://host3:6379?weight=2&read_timeout=2.5"
//
// session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if
// session.save_path can have a simple host:port format too, but you need to provide the tcp:// scheme if
// you want to use the parameters. The following parameters are available:
//
// - weight (integer): the weight of a host is used in comparison with the others in order to
// - weight (integer): the weight of a host is used in comparison with the others in order to
// customize the session distribution on several hosts. If host A has twice the weight of host B,
// it will get twice the amount of sessions. In the example, host1 stores 20% of all the
// sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/(1+2+2)). The target host is
// it will get twice the amount of sessions. In the example, host1 stores 20% of all the
// sessions (1/(1+2+2)) while host2 and host3 each store 40% (2/(1+2+2)). The target host is
// determined once and for all at the start of the session, and doesn't change. The default weight is 1.
// - timeout (float): the connection timeout to a redis host, expressed in seconds.
// If the host is unreachable in that amount of time, the session storage will be unavailable for the client.
// - timeout (float): the connection timeout to a redis host, expressed in seconds.
// If the host is unreachable in that amount of time, the session storage will be unavailable for the client.
// The default timeout is very high (86400 seconds).
// - persistent (integer, should be 1 or 0): defines if a persistent connection should be used.
// - prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored.
// - prefix (string, defaults to "PHPREDIS_SESSION:"): used as a prefix to the Redis key in which the session is stored.
// The key is composed of the prefix followed by the session ID.
// - auth (string, or an array with one or two elements): used to authenticate with the server prior to sending commands.
// - database (integer): selects a different database.
//
// Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime".
// You can change it with ini_set(). The session handler requires a version of Redis supporting EX and NX
// options of SET command (at least 2.6.12). phpredis can also connect to a unix domain socket:
// Sessions have a lifetime expressed in seconds and stored in the INI variable "session.gc_maxlifetime".
// You can change it with ini_set(). The session handler requires a version of Redis supporting EX and NX
// options of SET command (at least 2.6.12). phpredis can also connect to a unix domain socket:
// session.save_path = "unix:///var/run/redis/redis.sock?persistent=1&weight=1&database=0"
//

$savePath ??= ini_get('session.save_path');
$sessionName = $sessionOptions['name'] ?? ini_get('session.name');
$savePath ??= \ini_get('session.save_path');
$sessionName = $sessionOptions['name'] ?? \ini_get('session.name');

$savePathParts = explode('?', $savePath, 2);
parse_str($savePathParts[1] ?? '', $arguments);
Expand All @@ -72,25 +72,25 @@ public function __construct(string $savePath = null, array $sessionOptions = nul

//
// Session locking (from: https://github.com/phpredis/phpredis#session-locking)
//
//
// Support: Locking feature is currently only supported for Redis setup with single master instance
// (e.g. classic master/slave Sentinel environment).
// (e.g. classic master/slave Sentinel environment).
// So locking may not work properly in RedisArray or RedisCluster environments.
//
//
// Following INI variables can be used to configure session locking:
//
//; Should the locking be enabled? Defaults to: 0.
//redis.session.locking_enabled = 1
//; How long should the lock live (in seconds)? Defaults to: value of max_execution_time (defaults to 30).
//redis.session.lock_expire = 60
//; How long to wait between attempts to acquire lock, in microseconds (µs)?. Defaults to: 20000
//redis.session.lock_wait_time = 100000
//; Maximum number of times to retry (-1 means infinite). Defaults to: 100
//redis.session.lock_retries = 300
// ; Should the locking be enabled? Defaults to: 0.
// redis.session.locking_enabled = 1
// ; How long should the lock live (in seconds)? Defaults to: value of max_execution_time (defaults to 30).
// redis.session.lock_expire = 60
// ; How long to wait between attempts to acquire lock, in microseconds (µs)?. Defaults to: 20000
// redis.session.lock_wait_time = 100000
// ; Maximum number of times to retry (-1 means infinite). Defaults to: 100
// redis.session.lock_retries = 300
//

$lock_expire = (ini_get("redis.session.lock_expire") ?: ini_get("max_execution_time")) ?: 30; // 30s
$lock_wait_time = (ini_get("redis.session.lock_wait_time") ?: 20000); // 20ms
$lock_expire = (\ini_get('redis.session.lock_expire') ?: \ini_get('max_execution_time')) ?: 30; // 30s
$lock_wait_time = (\ini_get('redis.session.lock_wait_time') ?: 20000); // 20ms
$lock_retries = (int) ($lock_expire / ($lock_wait_time / 1000000)); // 1500x

ini_set('redis.session.locking_enabled', 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* @author Maurits van der Schee <maurits@vdschee.nl>
*
* @runTestsInSeparateProcesses
*
* @preserveGlobalState disabled
*/
class NativeMemcachedSessionHandlerTest extends TestCase
Expand All @@ -35,9 +36,9 @@ public function testConstruct(string $savePath, array $sessionOptions, string $e

new NativeSessionStorage($sessionOptions, new NativeMemcachedSessionHandler($savePath, $sessionOptions));

$this->assertEquals($expectedSessionName, ini_get('session.name'));
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$this->assertTrue((bool) ini_get('memcached.sess_locking'));
$this->assertEquals($expectedSessionName, \ini_get('session.name'));
$this->assertEquals($expectedSavePath, \ini_get('session.save_path'));
$this->assertTrue((bool) \ini_get('memcached.sess_locking'));
}

public function savePathDataProvider()
Expand All @@ -56,8 +57,8 @@ public function testConstructDefault()

new NativeSessionStorage([], new NativeMemcachedSessionHandler());

$this->assertEquals('localhost:11211', ini_get('session.save_path'));
$this->assertEquals('TESTING', ini_get('session.name'));
$this->assertTrue((bool) ini_get('memcached.sess_locking'));
$this->assertEquals('localhost:11211', \ini_get('session.save_path'));
$this->assertEquals('TESTING', \ini_get('session.name'));
$this->assertTrue((bool) \ini_get('memcached.sess_locking'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* @author Maurits van der Schee <maurits@vdschee.nl>
*
* @runTestsInSeparateProcesses
*
* @preserveGlobalState disabled
*/
class NativeRedisSessionHandlerTest extends TestCase
Expand All @@ -35,9 +36,9 @@ public function testConstruct(string $savePath, array $sessionOptions, string $e

new NativeSessionStorage($sessionOptions, new NativeRedisSessionHandler($savePath, $sessionOptions));

$this->assertEquals($expectedSessionName, ini_get('session.name'));
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$this->assertTrue((bool) ini_get('redis.session.locking_enabled'));
$this->assertEquals($expectedSessionName, \ini_get('session.name'));
$this->assertEquals($expectedSavePath, \ini_get('session.save_path'));
$this->assertTrue((bool) \ini_get('redis.session.locking_enabled'));
}

public function savePathDataProvider()
Expand All @@ -57,8 +58,8 @@ public function testConstructDefault()

new NativeSessionStorage([], new NativeRedisSessionHandler());

$this->assertEquals('tcp://localhost:6379?prefix=PHPREDIS_SESSION.TESTING.', ini_get('session.save_path'));
$this->assertEquals('TESTING', ini_get('session.name'));
$this->assertTrue((bool) ini_get('redis.session.locking_enabled'));
$this->assertEquals('tcp://localhost:6379?prefix=PHPREDIS_SESSION.TESTING.', \ini_get('session.save_path'));
$this->assertEquals('TESTING', \ini_get('session.name'));
$this->assertTrue((bool) \ini_get('redis.session.locking_enabled'));
}
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy