Tip: Cookie, set expiration value

1,237 views
Skip to first unread message

stu warneski

unread,
May 22, 2012, 9:42:12 PM5/22/12
to f3-fra...@googlegroups.com
I didn't see this in the official documentation page, so I'm posting it here for others to learn.

you can write a cookie that will last for the browsers session, using 
    F3::set('COOKIE.cookie_name', 'cookie_value');
example: to create a cookie named username, with a value of bong cosca...
    F3::set('COOKIE.username', 'bong cosca');

if you want to make that cookie stay on the users computer after they have left the website and their session has timed out, then you need to add 1 line of code before the F3::set

in F3, there is an array named JAR, which holds the default settings of PHP's cookie parameters such as expire, domina, path, http_only and secure.
the defaults for JAR are set in /lib/base.php
Expire defaults to a value of 0, which means it only lasts as long as the user's session is active.

the make the expires value longer, you can modify the property of the JAR array key named expire, using F3::set
    F3::set('JAR.expire', time() + 60 * 60 * 24 * 30);
    //then write the cookie.
    F3::set('COOKIE.username', $username);

the value being used for expire is the current time on the server, plus 60 seconds multiplied by 60 minutes, then 24 hours, then 30 days. So the cookie will last for 30 days before it expires.

Now JAR.expire will hold that value for the remainder of your script execution for the current server side. Then next script that is requested from the server, JAR.expire will be back to its default value because F3 bootstraps itself during afresh request. 

If you want to set a cookie that expires in 30 days use the above code.

if you need to set another cookie in the same script with a different value for expire, change the value of expire before writing the next cookie.
the make the cookie only last for the duration of the session, set JAR.expire equal to 0
    F3::set('JAR.expire', 0);

Hopes this helps somebody.


Justin Giesbrecht

unread,
Dec 12, 2013, 2:11:16 AM12/12/13
to f3-fra...@googlegroups.com
Thanks for that, appreciate it... you should update the code on the site inside GitHub

bcosca

unread,
Dec 12, 2013, 5:21:09 AM12/12/13
to f3-fra...@googlegroups.com
Latest commit in the dev branch makes this a lot easier.

F3::set('COOKIE.cookie_name', 'cookie_value', time() + 60 * 60 * 24 * 30); 

bcosca

unread,
Dec 12, 2013, 9:34:12 AM12/12/13
to f3-fra...@googlegroups.com
It's been improved further so it takes into account the current time as offset.

F3::set('COOKIE.cookie_name', 'cookie_value', 60 * 60 * 24 * 30);
Reply all
Reply to author
Forward
0 new messages