We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Set cookies in application bootstrap

Hi there,

I have a fully worked "remember me" feature in my Application that set some cookies with long expiration time in browser. (as explained in Vokuro sample)

I want to add some extra cookies for XSRF key and value, so I try to add those cookies in bootstrap file before $application->handle()->send(); line:

Bootstrap file

. . .
try {

    $application = new PhApplication($this->_di);

    $application->cookies->set('XSRF-TOKEN-KEY', $application->security->getTokenKey());
    $application->cookies->set('XSRF-TOKEN', $application->security->getToken());

    PhDi::setDefault($this->_di);
    $application->handle()->send();

} catch (PhException $e) {
    echo $e->getMessage();
} catch (\PDOException $e) {
    echo $e->getMessage();
}
. . .

but when I refresh page, the expiration time of "remember me" cookies change, so when I close browser and open it again, the auto-login does not work. When I remove XSRF-TOKEN line, every thing work perfectly.

How can I set some global, application-specific cookies? Is it about order of cookies settings?

Thanks

Hello, as far as i understood your problem, you do not need to set CSRF cookies, this is auto handled by Phalcon for you.

For example in my public forms i always have this:

<input type="hidden" name="{{ security.getTokenKey() }}" value="{{ security.getToken() }}"/> 

And in my php code:

if ($this->request->isPost() AND $this->security->checkToken()) {  

However, about remember me, functionality i would implement something like: When logging and user has checked the button "remember" you keep the session for logged and create a normal cookie in which you "encoded" info with wich you can log the user later. Simpliest example : md5(id + email + createdat_timestamp).

Next you can add a method in your BaseController which runs "before" other code is executed in which u check if there is NO logged session and your cookie exists, then you try to log user.