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)

 

One thought on “Magento cookies

  1. Thanks! Your code just helped me end about a day’s headache and confusion I was having with Magento’s cookie handling!

    My issue was that I was programmatically logging in a new customer (which ran from non-https), and for some reason Magento was only storing the cookie for the non-secure side, so as soon as the customer checked-out and it took you to the https secure side, it prompted the customer to log in again.

    My solution is a bit of a kludge work around, but it simply performs the log in, and then copies the cookies already set using the cookie set code you list above, but making sure http_only and secure is 0 as well as making sure the path is /.

    Now when you checkout, it keeps you logged in!

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *