SensacionRC
SensacionRC

Reputation: 615

Symfony 3.4 $_SESSION in controller

I have an app that starts in a .php file. In this file I do some work, but at the end I do two things, I generate a value and save in $_SESSION and redirect to other route:

This php file is out of Symfony folder:

<?php
session_start();

...Do some work

$_SESSION['token'] = 'some value';
header ("Location: new direction");
?>

The redirection,redirects to symfony folder,and starts the symfony part going to my src/AppBundle/Controller/MainController.

And in the first action that is processed in this controller I need to access the value of $_SESSION['token'] to do some work with this value in the controller action. This is the controller:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class MainController extends Controller
{
    public function homepageAction(Request $request)
    {
        dump($_SESSION);
        die;

        ...Some work
    }
}
?>

The dump($_SESSION) shows this:

enter image description here

But I can´t find my $_SESSION['token']

Do I need to use some Symfony component to access the PHP $_SESSION values inside a controller?

Or How can I access $_SESSION['token'] in the controller?

Upvotes: 0

Views: 1074

Answers (2)

SensacionRC
SensacionRC

Reputation: 615

I tryed all the things all of you suggest,and nothing convice me, so reading a post in a forum I fount this line:

php_value session.auto_start 0

I put that in my .htaccess file and Symfony doesn´t overwrite the $_SESSION variable anymore and I can access to it everywhere in the controllers.

Upvotes: 0

Adrien Rosi
Adrien Rosi

Reputation: 132

Best way is to create route that accept token param, to stuff like saving token param in session, and redirect user.

If you need to duplicate this behavior for all your routes, use a listener on request event.

Edit : More informations about my answer

Step 1 : Set your token value

Step 2 : Redirect to Symfony route that accept token param

Step 3 : Apply your own logic based on token value

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;


/**
 * @Route("/{token}", defaults={"token"=null})
 */
class MainController extends Controller
{

    public function homepageAction(Request $request, SessionInterface $session, ?string $token)
    {
        if ($token) {
            $session->set('token', $token);
        }

        ...Some work
    }
}

Upvotes: 1

Related Questions