How to use cookies from a component?

15,166
// Get input cookie object
$inputCookie  = JFactory::getApplication()->input->cookie;

// Get cookie data
$value        = $inputCookie->get($name = 'myCookie', $defaultValue = null);

// Check that cookie exists
$cookieExists = ($value !== null);

// Set cookie data
$inputCookie->set($name = 'myCookie', $value = '123', $expire = 0);

// Remove cookie
$inputCookie->set('myCookie', null, time() - 1);

Some rules about $expire value

  • its a Unix tinestamp in seconds, like return value of time().
  • $expire == 0: cookie lifetime is of browser session.
  • $expire < time(): cookie is being deleted (expire set to past). You could remove cookie by setting it's value to null, but apparently IE fails to do so.

Notes

Keep in mind that cookies should be set before headers are sent (usually before output is echoed).

Cookie key and value should be properly escaped

Non-string values

When serializing the value on set (like json_encode($dataNode)), remember to use proper filter to retrieve it later on. Default is cmd, which filters out pretty much anything but a-Z, 0-9 and cracks JSON structure.

// Get cookie data
$encodedString = $inputCookie->get('myCookie', null, $filter = 'string');

// Decode
$values = json_decode($encodedString);

// Encode and Set
$inputCookie->set('myCookie', json_encode($values));

Rererences

Share:
15,166
Ankur Alankar Biswal
Author by

Ankur Alankar Biswal

I am neither a geek nor a guru. I simply answer what I know, and learn what I don't know. I find SO a great place to learn and jump onto it whenever I get time.I strongly believe that "Everything you can imagine is real".

Updated on August 01, 2022

Comments

  • Ankur Alankar Biswal
    Ankur Alankar Biswal almost 2 years

    How can I use cookies in a Joomla component?

    setcookie( JUtility::getHash('JLOGIN_REMEMBER'), false, time() - 86400, '/' );
    

    Can anybody describe how this works?

  • Timo Huovinen
    Timo Huovinen over 10 years
    The value MUST NOT be an array, joomla does not support subcookies as of now
  • Mohd Abdul Mujib
    Mohd Abdul Mujib over 7 years
    @piotr_cz On the third line for the check if cookie exists, shouldn't the comparison operator be !== ?