Reputation: 1068
I want to getting session ID to store it in the database (because I store shopping carts in my database). Thereby, I want to get session ID, with this method:
$session = $this->get('session');
$carts->setSessionId($session->getId());
But this method returns an empty result. It's really weird because if I send this ID in my view with, for exemple:
'session' => $session->getId(),
It works... It's really strangely ; have I make an error in my code?
getSessionId() and setSessionId() functions:
/**
* Set sessionId
*
* @param string $sessionId
* @return Carts
*/
public function setSessionId($sessionId)
{
$this->sessionId = $sessionId;
return $this;
}
/**
* Get sessionId
*
* @return string
*/
public function getSessionId()
{
return $this->sessionId;
}
Thank you per advance!
Upvotes: 5
Views: 15422
Reputation: 99
The getId() method returns an empty string if the session has not been started yet. When starting the session manually, don't forget to check if the session hasn't been started already.
if(!$session->isStarted()) {
$session->start();
}
Upvotes: 1
Reputation: 52493
Please make sure your session has been started otherwise Session::getId() returns am empty string (''). See Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage
$session = $this->get('session');
$session->start();
$carts->setSessionId( $session->getId() );
Upvotes: 7