Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes
SessionManager Class Reference
Inheritance diagram for SessionManager:
SessionManagerInterface Session Session Session Quote Session Session Session Session Generic Session

Public Member Functions

 __construct (\Magento\Framework\App\Request\Http $request, SidResolverInterface $sidResolver, ConfigInterface $sessionConfig, SaveHandlerInterface $saveHandler, ValidatorInterface $validator, StorageInterface $storage, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager, \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory, \Magento\Framework\App\State $appState)
 
 writeClose ()
 
 __call ($method, $args)
 
 start ()
 
 isSessionExists ()
 
 getData ($key='', $clear=false)
 
 getSessionId ()
 
 getName ()
 
 setName ($name)
 
 destroy (array $options=null)
 
 clearStorage ()
 
 getCookieDomain ()
 
 getCookiePath ()
 
 getCookieLifetime ()
 
 setSessionId ($sessionId)
 
 getSessionIdForHost ($urlHost)
 
 isValidForHost ($host)
 
 isValidForPath ($path)
 
 regenerateId ()
 
 expireSessionCookie ()
 

Protected Member Functions

 registerSaveHandler ()
 
 _addHost ()
 
 _getHosts ()
 
 _cleanHosts ()
 
 clearSubDomainSessionCookie ()
 

Protected Attributes

 $defaultDestroyOptions = ['send_expire_cookie' => true, 'clear_storage' => true]
 
 $validator
 
 $request
 
 $sidResolver
 
 $sessionConfig
 
 $saveHandler
 
 $storage
 
 $cookieManager
 
 $cookieMetadataFactory
 

Static Protected Attributes

static $urlHostCache = []
 

Additional Inherited Members

- Data Fields inherited from SessionManagerInterface
const HOST_KEY = '_session_hosts'
 

Detailed Description

Session Manager @SuppressWarnings(PHPMD.CouplingBetweenObjects)

Definition at line 16 of file SessionManager.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Framework\App\Request\Http  $request,
SidResolverInterface  $sidResolver,
ConfigInterface  $sessionConfig,
SaveHandlerInterface  $saveHandler,
ValidatorInterface  $validator,
StorageInterface  $storage,
\Magento\Framework\Stdlib\CookieManagerInterface  $cookieManager,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory  $cookieMetadataFactory,
\Magento\Framework\App\State  $appState 
)
Parameters
\Magento\Framework\App\Request\Http$request
SidResolverInterface$sidResolver
ConfigInterface$sessionConfig
SaveHandlerInterface$saveHandler
ValidatorInterface$validator
StorageInterface$storage
\Magento\Framework\Stdlib\CookieManagerInterface$cookieManager
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory$cookieMetadataFactory
\Magento\Framework\App\State$appState
Exceptions

Definition at line 107 of file SessionManager.php.

117  {
118  $this->request = $request;
119  $this->sidResolver = $sidResolver;
120  $this->sessionConfig = $sessionConfig;
121  $this->saveHandler = $saveHandler;
122  $this->validator = $validator;
123  $this->storage = $storage;
124  $this->cookieManager = $cookieManager;
125  $this->cookieMetadataFactory = $cookieMetadataFactory;
126  $this->appState = $appState;
127  $this->start();
128  }

Member Function Documentation

◆ __call()

__call (   $method,
  $args 
)

Storage accessor method

Parameters
string$method
array$args
Returns
mixed
Exceptions

Definition at line 147 of file SessionManager.php.

148  {
149  if (!in_array(substr($method, 0, 3), ['get', 'set', 'uns', 'has'])) {
150  throw new \InvalidArgumentException(
151  sprintf('Invalid method %s::%s(%s)', get_class($this), $method, print_r($args, 1))
152  );
153  }
154  $return = call_user_func_array([$this->storage, $method], $args);
155  return $return === $this->storage ? $this : $return;
156  }
$method
Definition: info.phtml:13

◆ _addHost()

_addHost ( )
protected

Register request host name as used with session

Returns
$this

Definition at line 467 of file SessionManager.php.

468  {
469  $host = $this->request->getHttpHost();
470  if (!$host) {
471  return $this;
472  }
473 
474  $hosts = $this->_getHosts();
475  $hosts[$host] = true;
476  $_SESSION[self::HOST_KEY] = $hosts;
477  return $this;
478  }

◆ _cleanHosts()

_cleanHosts ( )
protected

Clean all host names that were registered with session

Returns
$this

Definition at line 495 of file SessionManager.php.

496  {
497  unset($_SESSION[self::HOST_KEY]);
498  return $this;
499  }

◆ _getHosts()

_getHosts ( )
protected

Get all host names where session was used

Returns
array

Definition at line 485 of file SessionManager.php.

486  {
487  return $_SESSION[self::HOST_KEY] ?? [];
488  }

◆ clearStorage()

clearStorage ( )

Unset all session data

Returns
$this

Implements SessionManagerInterface.

Definition at line 351 of file SessionManager.php.

352  {
353  $this->storage->unsetData();
354  return $this;
355  }

◆ clearSubDomainSessionCookie()

clearSubDomainSessionCookie ( )
protected

Expire the session cookie for sub domains

Returns
void

Definition at line 552 of file SessionManager.php.

553  {
554  foreach (array_keys($this->_getHosts()) as $host) {
555  // Delete cookies with the same name for parent domains
556  if ($this->sessionConfig->getCookieDomain() !== $host) {
557  $metadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
558  $metadata->setPath($this->sessionConfig->getCookiePath());
559  $metadata->setDomain($host);
560  $metadata->setSecure($this->sessionConfig->getCookieSecure());
561  $metadata->setHttpOnly($this->sessionConfig->getCookieHttpOnly());
562  $this->cookieManager->deleteCookie($this->getName(), $metadata);
563  }
564  }
565  }

◆ destroy()

destroy ( array  $options = null)

Destroy/end a session

Parameters
array$options
Returns
void

Implements SessionManagerInterface.

Definition at line 326 of file SessionManager.php.

327  {
328  $options = $options ?? [];
329  $options = array_merge($this->defaultDestroyOptions, $options);
330 
331  if ($options['clear_storage']) {
332  $this->clearStorage();
333  }
334 
335  if (session_status() !== PHP_SESSION_ACTIVE) {
336  return;
337  }
338 
339  session_regenerate_id(true);
340  session_destroy();
341  if ($options['send_expire_cookie']) {
342  $this->expireSessionCookie();
343  }
344  }

◆ expireSessionCookie()

expireSessionCookie ( )

Expire the session cookie

Sends a session cookie with no value, and with an expiry in the past.

Returns
void

Implements SessionManagerInterface.

Definition at line 574 of file SessionManager.php.

575  {
576  if (!$this->sessionConfig->getUseCookies()) {
577  return;
578  }
579 
580  $metadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
581  $metadata->setPath($this->sessionConfig->getCookiePath());
582  $metadata->setDomain($this->sessionConfig->getCookieDomain());
583  $metadata->setSecure($this->sessionConfig->getCookieSecure());
584  $metadata->setHttpOnly($this->sessionConfig->getCookieHttpOnly());
585  $this->cookieManager->deleteCookie($this->getName(), $metadata);
587  }

◆ getCookieDomain()

getCookieDomain ( )

Retrieve Cookie domain

Returns
string

Implements SessionManagerInterface.

Definition at line 362 of file SessionManager.php.

363  {
364  return $this->sessionConfig->getCookieDomain();
365  }

◆ getCookieLifetime()

getCookieLifetime ( )

Retrieve cookie lifetime

Returns
int

Implements SessionManagerInterface.

Definition at line 382 of file SessionManager.php.

383  {
384  return $this->sessionConfig->getCookieLifetime();
385  }

◆ getCookiePath()

getCookiePath ( )

Retrieve cookie path

Returns
string

Implements SessionManagerInterface.

Definition at line 372 of file SessionManager.php.

373  {
374  return $this->sessionConfig->getCookiePath();
375  }

◆ getData()

getData (   $key = '',
  $clear = false 
)

Additional get data with clear mode

Parameters
string$key
bool$clear
Returns
mixed

Definition at line 279 of file SessionManager.php.

280  {
281  $data = $this->storage->getData($key);
282  if ($clear && isset($data)) {
283  $this->storage->unsetData($key);
284  }
285  return $data;
286  }

◆ getName()

getName ( )

Retrieve session name

Returns
string

Implements SessionManagerInterface.

Definition at line 303 of file SessionManager.php.

304  {
305  return session_name();
306  }

◆ getSessionId()

getSessionId ( )

Retrieve session Id

Returns
string

Implements SessionManagerInterface.

Definition at line 293 of file SessionManager.php.

294  {
295  return session_id();
296  }

◆ getSessionIdForHost()

getSessionIdForHost (   $urlHost)

If session cookie is not applicable due to host or path mismatch - add session id to query

Parameters
string$urlHostcan be host or url
Returns
string {session_id_key}={session_id_encrypted} @SuppressWarnings(PHPMD.NPathComplexity)

Implements SessionManagerInterface.

Definition at line 409 of file SessionManager.php.

410  {
411  $httpHost = $this->request->getHttpHost();
412  if (!$httpHost) {
413  return '';
414  }
415 
416  $urlHostArr = explode('/', $urlHost, 4);
417  if (!empty($urlHostArr[2])) {
418  $urlHost = $urlHostArr[2];
419  }
420  $urlPath = empty($urlHostArr[3]) ? '' : $urlHostArr[3];
421 
422  if (!isset(self::$urlHostCache[$urlHost])) {
423  $urlHostArr = explode(':', $urlHost);
424  $urlHost = $urlHostArr[0];
425  $sessionId = $httpHost !== $urlHost && !$this->isValidForHost($urlHost) ? $this->getSessionId() : '';
426  self::$urlHostCache[$urlHost] = $sessionId;
427  }
428 
429  return $this->isValidForPath($urlPath) ? self::$urlHostCache[$urlHost] : $this->getSessionId();
430  }

◆ isSessionExists()

isSessionExists ( )

Does a session exist

Returns
bool

Implements SessionManagerInterface.

Definition at line 264 of file SessionManager.php.

265  {
266  if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
267  return false;
268  }
269  return true;
270  }

◆ isValidForHost()

isValidForHost (   $host)

Check if session is valid for given hostname

Parameters
string$host
Returns
bool

Implements SessionManagerInterface.

Definition at line 438 of file SessionManager.php.

439  {
440  $hostArr = explode(':', $host);
441  $hosts = $this->_getHosts();
442  return !empty($hosts[$hostArr[0]]);
443  }

◆ isValidForPath()

isValidForPath (   $path)

Check if session is valid for given path

Parameters
string$path
Returns
bool

Implements SessionManagerInterface.

Definition at line 451 of file SessionManager.php.

452  {
453  $cookiePath = trim($this->getCookiePath(), '/') . '/';
454  if ($cookiePath == '/') {
455  return true;
456  }
457 
458  $urlPath = trim($path, '/') . '/';
459  return strpos($urlPath, $cookiePath) === 0;
460  }

◆ regenerateId()

regenerateId ( )

Renew session id and update session cookie

Returns
$this

Implements SessionManagerInterface.

Definition at line 506 of file SessionManager.php.

507  {
508  if (headers_sent()) {
509  return $this;
510  }
511 
512  if ($this->isSessionExists()) {
513  // Regenerate the session
515  $newSessionId = session_id();
516  $_SESSION['new_session_id'] = $newSessionId;
517 
518  // Set destroy timestamp
519  $_SESSION['destroyed'] = time();
520 
521  // Write and close current session;
522  session_commit();
523 
524  // Called after destroy()
525  $oldSession = $_SESSION;
526 
527  // Start session with new session ID
528  session_id($newSessionId);
529  session_start();
530  $_SESSION = $oldSession;
531 
532  // New session does not need them
533  unset($_SESSION['destroyed']);
534  unset($_SESSION['new_session_id']);
535  } else {
536  session_start();
537  }
538 
539  $this->storage->init(isset($_SESSION) ? $_SESSION : []);
540 
541  if ($this->sessionConfig->getUseCookies()) {
543  }
544  return $this;
545  }

◆ registerSaveHandler()

registerSaveHandler ( )
protected

Register save handler

Returns
bool

Definition at line 247 of file SessionManager.php.

248  {
250  [$this->saveHandler, 'open'],
251  [$this->saveHandler, 'close'],
252  [$this->saveHandler, 'read'],
253  [$this->saveHandler, 'write'],
254  [$this->saveHandler, 'destroy'],
255  [$this->saveHandler, 'gc']
256  );
257  }

◆ setName()

setName (   $name)

Set session name

Parameters
string$name
Returns
$this

Implements SessionManagerInterface.

Definition at line 314 of file SessionManager.php.

315  {
316  session_name($name);
317  return $this;
318  }
if(!isset($_GET['name'])) $name
Definition: log.php:14

◆ setSessionId()

setSessionId (   $sessionId)

Specify session identifier

Parameters
string | null$sessionId
Returns
$this

Implements SessionManagerInterface.

Definition at line 393 of file SessionManager.php.

394  {
395  $this->_addHost();
396  if ($sessionId !== null && preg_match('#^[0-9a-zA-Z,-]+$#', $sessionId)) {
397  session_id($sessionId);
398  }
399  return $this;
400  }

◆ start()

start ( )

Configure session handler and start session

Exceptions

Implements SessionManagerInterface.

Definition at line 164 of file SessionManager.php.

165  {
166  if (!$this->isSessionExists()) {
167  \Magento\Framework\Profiler::start('session_start');
168 
169  try {
170  $this->appState->getAreaCode();
171  } catch (\Magento\Framework\Exception\LocalizedException $e) {
172  throw new \Magento\Framework\Exception\SessionException(
173  new \Magento\Framework\Phrase(
174  'Area code not set: Area code must be set before starting a session.'
175  ),
176  $e
177  );
178  }
179 
180  // Need to apply the config options so they can be ready by session_start
181  $this->initIniOptions();
182  $this->registerSaveHandler();
183  if (isset($_SESSION['new_session_id'])) {
184  // Not fully expired yet. Could be lost cookie by unstable network.
185  session_commit();
186  session_id($_SESSION['new_session_id']);
187  }
188  $sid = $this->sidResolver->getSid($this);
189  // potential custom logic for session id (ex. switching between hosts)
190  $this->setSessionId($sid);
191  session_start();
192  if (isset($_SESSION['destroyed'])
193  && $_SESSION['destroyed'] < time() - $this->sessionConfig->getCookieLifetime()
194  ) {
195  $this->destroy(['clear_storage' => true]);
196  }
197 
198  $this->validator->validate($this);
199  $this->renewCookie($sid);
200 
201  register_shutdown_function([$this, 'writeClose']);
202 
203  $this->_addHost();
204  \Magento\Framework\Profiler::stop('session_start');
205  }
206  $this->storage->init(isset($_SESSION) ? $_SESSION : []);
207  return $this;
208  }

◆ writeClose()

writeClose ( )

This method needs to support sessions with APC enabled

Returns
void

Implements SessionManagerInterface.

Definition at line 134 of file SessionManager.php.

135  {
136  session_write_close();
137  }

Field Documentation

◆ $cookieManager

$cookieManager
protected

Definition at line 83 of file SessionManager.php.

◆ $cookieMetadataFactory

$cookieMetadataFactory
protected

Definition at line 88 of file SessionManager.php.

◆ $defaultDestroyOptions

$defaultDestroyOptions = ['send_expire_cookie' => true, 'clear_storage' => true]
protected

Definition at line 27 of file SessionManager.php.

◆ $request

$request
protected

Definition at line 48 of file SessionManager.php.

◆ $saveHandler

$saveHandler
protected

Definition at line 69 of file SessionManager.php.

◆ $sessionConfig

$sessionConfig
protected

Definition at line 62 of file SessionManager.php.

◆ $sidResolver

$sidResolver
protected

Definition at line 55 of file SessionManager.php.

◆ $storage

$storage
protected

Definition at line 76 of file SessionManager.php.

◆ $urlHostCache

$urlHostCache = []
staticprotected

Definition at line 34 of file SessionManager.php.

◆ $validator

$validator
protected

Definition at line 41 of file SessionManager.php.


The documentation for this class was generated from the following file: