adit
adit

Reputation: 33644

how to access $_SESSION variable in symfony2

I am trying to do the following:

        $postfields = array_merge($_SERVER, array("p"=>$_POST, "s"=>$_SESSION));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, count($postfields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);

why isn't this working? It always gives me an error that $_SESSION does not exist.

Upvotes: 0

Views: 1909

Answers (3)

xurshid29
xurshid29

Reputation: 4210

the recommended way (in controller):

...

public function testAction(Request $request)
{
    $session = $request->getSession();
}

...

or by injecting RequestStack (in CustomService):

private $requestStack;

public function __construct(RequestStack $requestStack)
{
    $this->requestStack = $requestStack;
}

public function myMethod()
{
    $session = $this->requestStack->getCurrentRequest()->getSession();
}

Upvotes: 0

sjagr
sjagr

Reputation: 16502

Symfony uses a special session library that extends the PHP $_SESSION interface. To access all of the session attributes as a key => value array, you can use (from any controller/container):

$all_session_variables = $this->get('session')->all(); // Returns array() format

Or a specific session element using:

$key_session_variable = $this->get('session')->get('key'); // Returns the value stored in "key"

But this is only guaranteed to work assuming that you've previously set session variables using $this->get('session')->set().

Read more about Session Management here in the Symfony docs

Onto why you are getting a "$_SESSION does not exist" error: you haven't declared session_start()! Symfony hasn't done that for you either yet. But WAIT. Do NOT write that code since the same reference above states:

Symfony sessions are designed to replace several native PHP functions. Applications should avoid using session_start(), session_regenerate_id(), session_id(), session_name(), and session_destroy() and instead use the APIs in the following section.

You should instead use the Session library that Symfony provides because:

While it is recommended to explicitly start a session, a sessions will actually start on demand, that is, if any session request is made to read/write session data.

Upvotes: 2

akmozo
akmozo

Reputation: 9839

To get session try this into your controler :

$session = $this->get('session');

Upvotes: 1

Related Questions