Vael Victus
Vael Victus

Reputation: 4122

CakePHP set session via AJAX

I'm having a lot of trouble working with CakePHP sessions and AJAX. I have an AJAX login that I use Auth->login() with, and then I add some extra parameters to the end with Session->write().

$this->Auth->login();
$this->Session->write('Auth.User.id', $user_grab['User']['id']);
$this->Session->write('Auth.User.auth_level', $user_grab['User']['auth_level']);
$this->Session->write('Auth.User.successful', 3);

I am using Configure::write('Session.checkAgent', false); as per some suggestions I've read.

The problem is any time I set inside this AJAX, it won't be there on any other page load: even if I do the AJAX again, after writing, and just do a read(), the read() will be empty. It's as if it just ignores the AJAX completely. Yet if I:

 ...    

 $this->Session->write('Auth.User.successful', 3);

 print_r($this->Session->read());

I will see what's supposed to be in the session, it just won't truly save. I can save anywhere else in non-ajax parts of the application, even just setting test session data on the index of the site. It persists.

I'm completely stuck. It seems unrelated to using Auth->login(). I am using, in AppController, both Session and Auth.

Expected behavior: being able to Session->write() in AJAX and have what I wrote be available anywhere else. To test, I was using a test action with a simple debug($_SESSION) and debug($this->Session->read()).

Upvotes: 0

Views: 1238

Answers (1)

Vael Victus
Vael Victus

Reputation: 4122

It was something stupid. I want to document here for others' reference:

It had to do with the www subdomain. I happened to leave it out in various places throughout the process, including the AJAX request itself, and this warranted a new session only accessible through www. This isn't exclusive to Cake, but I think it's an important factor to note for anyone going through something similar that is not easily reproduced on a local machine.

FYI, you can force www throughout the domain via your .htaccess:

<IfModule mod_rewrite.c>
   RewriteEngine on

   RewriteCond %{HTTPS} off
   RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
   RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

   RewriteCond %{HTTPS} on
   RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
   RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

Upvotes: 0

Related Questions