Magento: Create, Read, Delete Cookie

Here is the code to create, read, and delete cookie in Magento.

Mage_Core_Model_Cookie class contains functions to set, get and delete cookie.


/**
 * set cookie
 * name and value are mandatory; other parameters are optional and can be set as null
 * $period = cookie expire date
 */
 Mage::getModel('core/cookie')->set($name, $value, $period, $path, $domain, $secure, $httponly);
/**
 * get cookie with a specific name
 * $name = name of the cookie
 */
 Mage::getModel('core/cookie')->get($name);
 /**
 * get all cookies as an array
 */
 Mage::getModel('core/cookie')->get();
 /**
 * delete/remove cookie
 * $name is mandatory; other parameters are optional and cen be set as null
 */
 Mage::getModel('core/cookie')->delete($name, $path, $domain, $secure, $httponly);

You can get cookie expire date, path, domain, secure, httponly from the following Magento code.


$cookieExpires = Mage::getModel('core/cookie')->getLifetime($cookieName);
$cookiePath = Mage::getModel('core/cookie')->getPath($cookieName);
$cookieDomain = Mage::getModel('core/cookie')->getDomain($cookieName);
$cookieSecure = Mage::getModel('core/cookie')->isSecure($cookieName);
$cookieHttponly = Mage::getModel('core/cookie')->getHttponly($cookieName);

Example / Usuage:-


$name = 'test';
$value = 'mukesh';

// set cookie
Mage::getModel('core/cookie')->set($name, $value);

// print cookie value
echo Mage::getModel('core/cookie')->get($name);

// print cookie lifetime or period
// by default the period is set as 3600 seconds
echo Mage::getModel('core/cookie')->getLifetime($name);

// you can set different period value as well
$name = 'test2';
$value = 'chapagain';
$period = 7200;
Mage::getModel('core/cookie')->set($name, $value, $period);

Hope it helps. Thanks.