XF 2.0 XF2 and Cookies Management (via ->setCookie) issues

Scandal

Well-known member
Hello all!
I have some strange issues with cookies management in XF2 development.

A) I try to use this code inside a Pub Controller before the exit of the script (it is an Ajax request and I need just to return '1'):
PHP:
// do and checking things
$this->app()->response->setCookie('mycookie', 'lalala', time()+3600*24, null, true);                 
exit('1');
... but the cookie is not set.
Basically I do this: make an ajax request -> if all ok inside the ajax code I set the cookie first and then exit with "1" -> in front end, when the javascript function see "1" as return, do a location.reload(). On this new page I need the mycookie to have a value and accessible via php.
But it seems the cookie is never created or get a value.
I use this as debug code to see the current page cookies:
PHP:
            $getcookies = $this->request->getCookies();
            var_dump($getcookies);

B) The other strange is that if I do this before the pre-noticed location.reload() :
Code:
            success: function(data, textStatus, jqXHR){
                    if (data == '1')
                    {
                        XF.Cookie.set('mycookie', 'lala');         
                        location.reload();
                    }
... it will work only if the cookie is not exists (= it works only for first time).

But anyway, I want to control cookies only via PHP. Why I can't run a $this->app()->response->setCookie inside a pub controller? or how I could? :)

I need to run both ->setCookie() and removeCookie() as declared @ src\XF\Http\Reponse.php
 
Any idea? Very strange issue.
I tried also default php function setcookie() but the issue remains. :)
 
Calling the "setCookie" method does not immediately send a cookie header. Instead, the Response class remembers the supplied values and only sends the cookie once it's "send" method is called (which never happens if you abort the execution by calling "exit" immediately after "setCookie").

I think you should generate the whole response using XenForo's Response class. (It should be possible to figure this out by reading the XenForo source code. Or maybe someone else can help. I haven't done this myself and spontaneously don't have a code example. But maybe I was able to point you into the right direction)
 
Great tip Steffen!

Well, I was taking a look on Response class. I detected that this is a functionable solution (on my example: just to exit with '1') :
PHP:
                echo $this->app()->response->contentType('text/plain')->body('1')->send();
                exit;
... once previously to that code, I can run with success also the setCookie.

Thanks again.
 
Top Bottom