Magento cookies

Cookies in Magento are easy to work with. There may be a need to use cookies to pass data to or from Magento whether it is to identify users, track users or some other case.

The Magento core has a cookie model to set, get and delete cookies.  So let’s get started with the code and some descriptions for usage.

Set a cookie in Magento

Mage::getModel('core/cookie')->set($name, $value, $period, $path, $domain, $secure, $httponly);

$name – the cookie name, is required
$value – the cookie value, is required
$period – the cookie lifetime (in seconds – default is 3600)
$path – the cookie path (make cookie available to a different directory. For whole domain set to / – defaults to path you are in when setting cookie)
$domain – the cookie domain (is it available to sub domains)
$secure – the cookie is for secured areas using SSL / HTTPS (values accepted int or bool – 1, 0, true, false)
$httponly – the cookie can only be retrieved through HTTP protocol. Not javascript, etc.. (values accepted bool – true, false)

Get a cookie in Magento

Mage::getModel(‘core/cookie’)->get($name);

This will get the cookie value for cookie $name

To get an array of all cookies use:

Mage::getModel('core/cookie')->get();

Delete a cookie in Magento

To remove a cookie use:

Mage::getModel(‘core/cookie’)->delete($name, $path, $domain, $secure, $httponly);

$name – the cookie name, is required
$path – the cookie path (make cookie available to a different directory. For whole domain set to / – defaults to path you are in when setting cookie)
$domain – the cookie domain (is it available to sub domains)
$secure – the cookie is for secured areas using SSL / HTTPS (values accepted int or bool – 1, 0, true, false)
$httponly – the cookie can only be retrieved through HTTP protocol. Not javascript, etc.. (values accepted bool – true, false)