Session and cookies

Sessions in Magento conform to MagentoFrameworkSessionSessionManagerInterface. In the app/etc/di.xml file, there is a definition preference for the SessionManagerInterface class which points to the MagentoFrameworkSessionGeneric class type. The SessionGeneric class is just an empty class that extends the MagentoFrameworkSessionSessionManager class, which in turn implements the SessionManagerInterface class.

There is one important object that gets instantiated in the SessionManager instance that conforms to MagentoFrameworkSessionConfigConfigInterface. On looking at app/etc/di.xml file, we can see a preference for ConfigInterface pointing to a MagentoFrameworkSessionConfig class type.

Tip

To fully understand the session behavior in Magento, we should study the inner workings of both the SessionManager and SessionConfig classes.

Magento uses cookies to keep track of a session. These cookies have a default lifetime of 3,600 seconds. When a session is established, a cookie with the name of PHPSESSID is created in the browser. The value of the cookie equals the session name. By default, sessions are stored in files in the var/session directory of Magento's root installation.

If you have a look at these session files, you will see that session information is being stored in serialized strings that are divided into groupings such as _session_validator_data, _session_hosts, default, customer_website_1, and checkout, as shown in the following screenshot:

Session and cookies

This is not the finite list of grouping. Modules that implement their own session handling bits can add their own groups.

We can store and retrieve information in a session by simply using expressions like the following ones:

$this->sessionManager->setFoggylineOfficeVar1('Office1');
$this->sessionManager->getFoggylineOfficeVar1();

The preceding expressions will create and get an entry from the session under the default group.

We can get the entire content of the default session group simply by using the $this->sessionManager->getData() expression, which will return an array of data that is similar to the following one:

array(3) {
  ["_form_key"] => string(16) "u3sNaa26Ii21nveV"
  ["visitor_data"] => array(14) {
    ["last_visit_at"] => string(19) "2015-08-19 07:40:03"
    ["session_id"] => string(26) "8p82je0dkqq1o00lanlr6bj6m2"
    ["visitor_id"] => string(2) "35"
    ["server_addr"] => int(2130706433)
    ["remote_addr"] => int(2130706433)
    ["http_secure"] => bool(false)
    ["http_host"] => string(12) "magento2.loc"
    ["http_user_agent"] => string(121) "Mozilla/5.0 …"
    ["http_accept_language"] => string(41) "en-US,en;"
    ["http_accept_charset"] => string(0) ""
    ["request_uri"] => string(38) "/index.php/foggyline_office/test/crud/"
    ["http_referer"] => string(0) ""
    ["first_visit_at"] => string(19) "2015-08-19 07:40:03"
    ["is_new_visitor"] => bool(false)
  }
  ["foggyline_office_var_1"] => string(7) "Office1"
}

As you can see, the foggyline_office_var_1 value is right there among other session values.

There are several useful methods of ConfigInterface that we can use to fetch session configuration information; a few of these methods are as follows:

  • getCookieSecure
  • getCookieDomain
  • getCookieHttpOnly
  • getCookieLifetime
  • getName
  • getSavePath
  • getUseCookies
  • getOptions

Here's a result example of the getOptions method call on the SessionConfig instance:

array(9) {
  ["session.save_handler"] => string(5) "files"
  ["session.save_path"] => string(39) "/Users/branko/www/magento2/var/session/"
  ["session.cookie_lifetime"] => int(3600)
  ["session.cookie_path"] => string(1) "/"
  ["session.cookie_domain"] => string(12) "magento2.loc"
  ["session.cookie_httponly"] => bool(true)
  ["session.cookie_secure"] => string(0) ""
  ["session.name"] => string(9) "PHPSESSID"
  ["session.use_cookies"] => bool(true)
}

Cookies often go hand in hand with sessions. Besides being used to link to a certain session, cookies are often used to store some information on the client side, thus tracking or identifying the return users and customers.

Besides the pure PHP approach with the setcookie function, we can manage cookies in Magento through an instance of MagentoFrameworkStdlibCookieManagerInterface. When you look at app/etc/di.xml file, you will see that the preference for CookieManagerInterface points to a class of the MagentoFrameworkStdlibCookiePhpCookieManager type.

The following restrictions are worth noting when it comes to Magento cookies:

  • We can set maximum of 50 cookies in the system. Otherwise, Magento will throw an Unable to send the cookie. Maximum number of cookies would be exceeded exception.
  • We can store a cookie with a maximum size of 4096 bytes. Otherwise, Magento will throw an Unable to send the cookie. Size of '%name' is %size bytes exception.

By imposing these restrictions, Magento ensures that we are compatible with most browsers.

The CookieManagerInterface class, among other things, specifies the setSensitiveCookie method requirement. This method sets a value in a private cookie with the given $name $value pairing. Sensitive cookies have HttpOnly set to true and thus cannot be accessed by JavaScript.

As we will soon demonstrate in the following examples, to set a public or private cookie, we can help ourselves by using instances of the following:

  • MagentoFrameworkStdlibCookieCookieMetadataFactory
  • MagentoFrameworkStdlibCookieManagerInterface
  • MagentoFrameworkSessionConfigConfigInterface

We can set public cookies in the following way:

$cookieValue = 'Just some value';
$cookieMetadata = $this->cookieMetadataFactory
    ->createPublicCookieMetadata()
    ->setDuration(3600)
    ->setPath($this->sessionConfig->getCookiePath())
    ->setDomain($this->sessionConfig->getCookieDomain())
    ->setSecure($this->sessionConfig->getCookieSecure())
    ->setHttpOnly($this->sessionConfig->getCookieHttpOnly());

$this->cookieManager
  ->setPublicCookie('cookie_name_1', $cookieValue, $cookieMetadata);

The preceding code will result in a cookie, as shown in the following screenshot:

Session and cookies

We can set private cookies in the following way:

$cookieValue = 'Just some value';

$cookieMetadata = $this->cookieMetadataFactory
    ->createSensitiveCookieMetadata()
    ->setPath($this->sessionConfig->getCookiePath())
    ->setDomain($this->sessionConfig->getCookieDomain());

$this->cookieManager
  ->setSensitiveCookie('cookie_name_2', $cookieValue, $cookieMetadata);

The preceding code will result in a cookie, as shown in the following screenshot:

Session and cookies

Interestingly, both the public and private cookies in the preceding example show that HttpOnly is checked off because by default, a Magento admin has Stores | Settings | Configuration | General | Web | Default Cookie Settings | Use HTTP Only set to Yes. Since we are using the setHttpOnly method in the public cookie example, we simply picked up the config value via $this->sessionConfig->getCookieHttpOnly() and passed it on. If we comment out that line, we will see that the public cookie does not really set HttpOnly by default.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.137.17