Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 sessions not persisting after created via AJAX call

Let me give you the scenario. I have an AJAX call that calls /auth - that page in turn checks if the user is authenticated and sets a couple session variables (code below).

$session = $this->getRequest()->getSession();

$session->set('fbid', $fbid);
$session->set('name', $name);

// not sure if this is even needed - get the same with or without
//$session->save();

Now if I go to another page and try to access that session, it comes back empty.

If I set those sessions on a regular page (not one accessed via XMLHttpRequest/AJAX), it works fine.

Here are my session settings in config.yml:

session:         
    cookie_lifetime:         3600
    cookie_httponly:         false

I thought that the problem may have been httponly, but that didn't do it.

Any suggestions? Am I missing something?

* UPDATE *

Here is my security/firewall settings:

firewalls:
    dev:
        pattern:  ^/(_(profiler|wdt)|css|images|js)/
        security: false

    login:
        pattern:  ^/demo/secured/login$
        security: false

    secured_area:
        pattern:    ^/demo/secured/
        form_login:
            check_path: /demo/secured/login_check
            login_path: /demo/secured/login
        logout:
            path:   /demo/secured/logout
            target: /demo/

I haven't changed the firewall settings at all, and from what I can tell, it shouldn't be affecting the /auth call via XMLHttpRequest.

* Update 2 *

I ended up adding $session->shutdown() after the 2 sets (and yes I know that shutdown isn't a Session object method). It ended up getting an error, but because of that it started working and it actually saved it to $_SESSION. So, if that error forced it to save to $_SESSION, there has to be an actual method that forces the save. Really odd..

like image 261
xil3 Avatar asked Dec 26 '22 17:12

xil3


1 Answers

I figured out what the problem was.

The first session was being created on the production environment (the action called via AJAX / XMLHttpRequest), and the next page that I was testing it on was actually on the development environment. At the time, it never crossed my mind that Symfony 2 was actually saving the sessions for prod and dev in different spots - PHP usually has a default location where it saves them all.

Symfony 2 overwrites the default session.save_path and puts it's own for each - wasted a day before I found this out, unfortunately.

Also wrote an article on it, so others don't have to go through the same problem.

http://jondev.net/articles/Reasons_why_Symfony_2_sessions_might_not_always_persist

like image 173
xil3 Avatar answered Jan 05 '23 11:01

xil3