Tag Archives: session

Using cookies in Lithium PHP

RDO Calender required me to use cookies to keep track of simple session information. For a while I couldn’t figure it out but after reading the unit tests I got it.

Configuration

Instead of using the $_COOKIE superglobal you can use Lithium’s Session adapter to create a cookie adapter then use inside your controllers. First start off by setting up the adapter in the configuration file.
app/config/bootstrap/session.php (make sure the session.php file is uncommented in app/config/bootstrap/bootstrap.php)

Session::config(array(
	'cookie' => array('adapter' => 'Cookie', 'expire' => '+365 day'),
	'default' => array('adapter' => 'Php')
));

Below are all the options, taken from libraries/lithium/storage/session/adapter/Cookie.php

	/**
	 * Default settings for this session adapter.
	 *
	 * @var array Keys are in direct correspondence with the parameters in the PHP-native
	 *      `setcookie()` method. The only difference is that the `expire` value is a
	 *		strtotime-compatible string instead of an epochal timestamp.
	 */
	protected $_defaults = array(
		'expire' => '+2 days', 'path' => '/', 'name' => null,
		'domain' => '', 'secure' => false, 'httponly' => false
	);

Read/Write

After the setup is done, you can read and write cookies using the Session::read and Session:write functions respectively.

Session::read($key = null, array $options = array());
Session::write($key, $value = null, array $options = array());

It’s fairly straightforward. In options you’ll have to specify the cookie that you created. Full Session::read example below.

Session::read('cal.dow', array('name' => 'cookie'));

where ‘cookie’ is the name of the adapter we created in the config.

Lithium PHP uses the ‘.’ character to give namespaces to the cookie keys. Each key is broken into sections and restructured using ‘[‘ and ‘]’. The call above will read the cookie of key “appcookie[cal][dow]”

JQuery cookie plugin

Because I was using the jquery.cookie.js plugin in conjunction; I want to point out that the plugin (and possibly others) use encodeURIComponent() to escape keys/values when setting cookies. This escaped the ‘[]’ characters used by lithium. I modified the aforementioned plugin to accept a rawKey parameter that will prevent the key from being escaped.
relevant excerpt:

return (document.cookie = [
            options.rawKey? key : encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));