Magento 2 – How to Get SID Programmatically

magento2.1.5sessionurl

I am working on multi store

Store > Configuration > General > Web > Session Validation Settings >
Use SID on Storefront is set to "Yes" allow customer to stay logged in
when switching between different stores.

enter image description here

However I am not getting SID in my front end URL. Is there any way to get SID pragmatically and append to front end URL.

Best Answer

I think you can get get Session from getSessionId() Using

Magento\Framework\Session\Config\ConfigInterface\SessionManager

How session is appended to url you can refer to createUrl() in

Magento\Framework\Url

It appends throught _prepareSessionUrl()

/**
 * Check and add session id to URL
 *
 * @param string $url
 *
 * @return \Magento\Framework\UrlInterface
 */
protected function _prepareSessionUrl($url)
{
    if (!$this->getUseSession()) {
        return $this;
    }
    $sessionId = $this->_session->getSessionIdForHost($url);
    if ($this->_sidResolver->getUseSessionVar() && !$sessionId) {
        $this->setQueryParam('___SID', $this->_isSecure() ? 'S' : 'U');
    } elseif ($sessionId) {
        $this->setQueryParam($this->_sidResolver->getSessionIdQueryParam($this->_session), $sessionId);
    }
    return $this;
}