Note: each tutorial contains information about one specific part of Spoon. If something is unclear, post a comment.

Cookie

Written by Tijs Verkoyen -

Prerequisites

What will you learn?

  • Store data in a cookie
  • Retrieve data from a cookie

Tutorial

Cookie basics

Cookies are used quite often to store data on the clients' computer for later use. SpoonCookie only has static functions, so you don't have to create an instance. So if you want to store some data in a cookie, use the set method. To retrieve that data, use the get method. If you want to check if one or more cookies exist, use the exists method.

SpoonCookie serializes the data when setting a cookie and attempts to deserialize it when retrieving the value. That means that you have to watch out when you manually try to set a cookie with PHP's native setcookie function and attempt to retrieve that value with SpoonCookie.

The example below stores the values of the variable $foo in a cookie.

// required classes
require_once 'spoon/spoon.php';

// init var
$foo = 'Wut the dilly joo';

// store cookie
SpoonCookie::set('foo', $foo);

Retrieving the data stored in the cookie named 'foo'. When checking if a cookie exists, it's possible to check multiple cookies at once. Only if all the keys were internally found in $_COOKIE, then the result will be true.

// does this cookie exist?
if(SpoonCookie::exists('foo'))
{
    // show cookie contents
    Spoon::dump(SpoonCookie::get('foo'), false);
}

// multiple checks
if(SpoonCookie::exists('foo', 'bar', 'spoon'))
{
    // it seems like all 3 cookies are present
}

When you want to delete one or more cookies.

// delete one cookie
SpoonCookie::delete('foo');

// delete multiple cookies
SpoonCookie::delete('foo', 'foo2', 'foo3');

Advanced

Storing a cookie for more than 24 hours

By default a cookie is stored 24 hours. If you want to store it for a longer period, you need to manually set the time, expressed in seconds.

// set a cookie for 30 days
SpoonCookie::set('foo', 'bar', (30 * 24 * 60 * 60));

Making the cookie only available in the subdirectory /foo

// set a cookie for a specific subdirectory
SpoonCookie::set('foo', 'bar', 86400, '/foo');

Make the cookie available on all subdomains

// set a cookie for all subdomains
SpoonCookie::set('foo', 'bar', 86400, '/', '.example.com');

Make sure that the cookie only travels over HTTPS

// set a cookie that will only travel over https
SpoonCookie::set('foo', 'bar', 86400, '/', '.example.com', true);

Conclusion

As you can see in the code examples, SpoonCookie is a simplified version of PHP's setcookie and $_COOKIE variable. This class works very similar as SpoonSession.